diff --git a/.github/workflows/bindgen.yml b/.github/workflows/bindgen.yml index 21f96aed27..1778de1d2b 100644 --- a/.github/workflows/bindgen.yml +++ b/.github/workflows/bindgen.yml @@ -12,74 +12,61 @@ on: - main jobs: - rustfmt-clippy: + rustfmt: runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - - name: Install stable - uses: actions-rs/toolchain@v1 + - name: Install nightly + uses: dtolnay/rust-toolchain@master with: - profile: minimal - # TODO: Should ideally be stable, but we use some nightly-only - # features. toolchain: nightly - override: true - components: rustfmt, clippy + components: rustfmt - name: Run rustfmt - uses: actions-rs/cargo@v1 - with: - command: fmt - args: -- --check + run: cargo +nightly fmt -- --check + + clippy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 - name: Run clippy - uses: actions-rs/cargo@v1 - with: - command: clippy - args: --tests + run: cargo clippy --all-targets --workspace --exclude bindgen-integration --exclude tests_expectations -- -D warnings msrv: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + + - name: Read crate metadata + id: metadata + run: echo "rust-version=$(sed -ne 's/rust-version *= *\"\(.*\)\"/\1/p' Cargo.toml)" >> $GITHUB_OUTPUT - name: Install msrv for lib uses: dtolnay/rust-toolchain@master with: - # MSRV below is documented in Cargo.toml and README.md, please update those if you - # change this. - toolchain: 1.60.0 + toolchain: ${{ steps.metadata.outputs.rust-version }} - name: Test lib with msrv - run: cargo +1.60.0 test --package bindgen + run: cargo +${{ steps.metadata.outputs.rust-version }} test --package bindgen - name: Install msrv for cli uses: dtolnay/rust-toolchain@master with: - # MSRV below is documented in Cargo.toml and README.md, please update those if you - # change this. - toolchain: 1.64.0 + toolchain: ${{ steps.metadata.outputs.rust-version }} - name: Test cli with msrv - run: cargo +1.64.0 build --package bindgen-cli + run: cargo +${{ steps.metadata.outputs.rust-version }} build --package bindgen-cli minimal: runs-on: ubuntu-latest env: RUSTFLAGS: -D warnings steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - - name: Install stable - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true - - - name: Check without default features + - name: Check without default features run: cargo check -p bindgen --no-default-features --features=runtime docs: @@ -87,16 +74,9 @@ jobs: env: RUSTDOCFLAGS: -D warnings steps: - - uses: actions/checkout@v3 - - - name: Install stable - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true + - uses: actions/checkout@v4 - - name: Generate documentation for `bindgen` + - name: Generate documentation for `bindgen` run: cargo doc --document-private-items --no-deps -p bindgen - name: Generate documentation for `bindgen-cli` @@ -105,14 +85,7 @@ jobs: quickchecking: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - - name: Install stable - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true + - uses: actions/checkout@v4 # TODO: Actually run quickchecks once `bindgen` is reliable enough. - name: Build quickcheck tests @@ -124,14 +97,7 @@ jobs: matrix: os: [ubuntu-latest, macos-latest] steps: - - uses: actions/checkout@v3 - - - name: Install stable - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true + - uses: actions/checkout@v4 - name: Test expectations run: cd bindgen-tests/tests/expectations && cargo test @@ -141,12 +107,7 @@ jobs: strategy: matrix: os: [ubuntu-latest] - target: - - debian: null - cross: null - rust: null llvm_version: ["9.0", "16.0"] - main_tests: [1] release_build: [0, 1] no_default_features: [0, 1] # FIXME: There are no pre-built static libclang libraries, so the @@ -163,93 +124,42 @@ jobs: no_default_features: 0 feature_extra_asserts: 1 - # FIXME: Seems installing multiarch packages fails: - # - # https://github.com/rust-lang/rust-bindgen/pull/2037/checks?check_run_id=2441799333 - # - # - os: ubuntu-latest - # target: - # debian: arm64 - # cross: aarch64-linux-gnu - # rust: aarch64-unknown-linux-gnu - # llvm_version: "16.0" - # main_tests: 0 - # release_build: 0 - # feature_extra_asserts: 0 - # Ensure stuff works on macos too - # FIXME: Ideally should use the latest llvm version, but llvm doesn't - # provide releases for x86-64 macOS anymore which is what the runner uses. - # - os: macos-latest - llvm_version: "9.0" + llvm_version: "16.0" release_build: 0 no_default_features: 0 feature_extra_asserts: 0 steps: - - uses: actions/checkout@v3 - - - name: Install multiarch packages - if: matrix.target.debian - run: | - sudo apt-get install binfmt-support qemu-user-static gcc-${{matrix.target.cross}} g++-${{matrix.target.cross}} - source /etc/lsb-release - sudo tee /etc/apt/sources.list </dev/null - deb [arch=${{matrix.target.debian}}] http://ports.ubuntu.com/ubuntu-ports/ $DISTRIB_CODENAME main - deb [arch=${{matrix.target.debian}}] http://ports.ubuntu.com/ubuntu-ports/ $DISTRIB_CODENAME-updates main - deb [arch=${{matrix.target.debian}}] http://ports.ubuntu.com/ubuntu-ports/ $DISTRIB_CODENAME-backports main - deb [arch=${{matrix.target.debian}}] http://ports.ubuntu.com/ubuntu-ports/ $DISTRIB_CODENAME-security main - EOF - sudo dpkg --add-architecture ${{matrix.target.debian}} - sudo apt-get update - sudo apt-get install libc6:${{matrix.target.debian}} libstdc++6:${{matrix.target.debian}} + - uses: actions/checkout@v4 - name: Install stable - uses: actions-rs/toolchain@v1 + uses: dtolnay/rust-toolchain@master with: - profile: minimal toolchain: stable - target: ${{matrix.target.rust}} - override: true - name: Install libtinfo if: matrix.os == 'ubuntu-latest' run: | - sudo apt-get update - sudo apt-get install libtinfo5 + wget https://mirrors.kernel.org/ubuntu/pool/universe/n/ncurses/libtinfo5_6.3-2ubuntu0.1_amd64.deb + sudo dpkg -i libtinfo5_6.3-2ubuntu0.1_amd64.deb + - name: Install LLVM and Clang + uses: KyleMayes/install-llvm-action@v2.0.5 + with: + version: ${{matrix.llvm_version}} - name: Run all the tests env: GITHUB_ACTIONS_OS: ${{matrix.os}} - RUST_CROSS_COMPILER: ${{matrix.target.cross}} - RUST_TARGET: ${{matrix.target.rust}} - LLVM_VERSION: ${{matrix.llvm_version}} - BINDGEN_MAIN_TESTS: ${{matrix.main_tests}} BINDGEN_RELEASE_BUILD: ${{matrix.release_build}} BINDGEN_FEATURE_RUNTIME: ${{matrix.feature_runtime}} BINDGEN_FEATURE_EXTRA_ASSERTS: ${{matrix.feature_extra_asserts}} BINDGEN_NO_DEFAULT_FEATURES: ${{matrix.no_default_features}} + BINDGEN_RUST_FOR_LINUX_TEST: ${{matrix.os == 'ubuntu-latest' && matrix.llvm_version == '16.0' && matrix.feature_extra_asserts == 0 && 1 || 0}} run: ./ci/test.sh - check-cfg: - runs-on: ubuntu-latest - env: - RUSTFLAGS: -D warnings - steps: - - uses: actions/checkout@v3 - - - name: Install nightly - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: nightly - override: true - - - name: Check cfg - run: cargo check -Z unstable-options -Z check-cfg - test-book: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 # NOTE(emilio): Change deploy-book as well if you change this. - name: Test book @@ -258,12 +168,27 @@ jobs: ./mdbook build book ./mdbook test book + # FIXME(pvdrz): this should be done inside `bindgen-test` instead + test-no-headers: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Test `--help` + run: cargo run -- --help + + - name: Test `--version` + run: cargo run -- --version + + - name: Test `--generate-shell-completions` + run: cargo run -- --generate-shell-completions=bash + # One job that "summarizes" the success state of this pipeline. This can then # be added to branch protection, rather than having to add each job # separately. success: runs-on: ubuntu-latest - needs: [rustfmt-clippy, msrv, minimal, docs, quickchecking, test-expectations, test, check-cfg, test-book] + needs: [rustfmt, clippy, msrv, minimal, docs, quickchecking, test-expectations, test, test-book, test-no-headers] # GitHub branch protection is exceedingly silly and treats "jobs skipped # because a dependency failed" as success. So we have to do some # contortions to ensure the job fails if any of its dependencies fails. diff --git a/.github/workflows/bump-version.yml b/.github/workflows/bump-version.yml new file mode 100644 index 0000000000..56a264f7f7 --- /dev/null +++ b/.github/workflows/bump-version.yml @@ -0,0 +1,68 @@ +name: Bump version for release + +on: + workflow_dispatch: + inputs: + level: + description: | + Select the level of the release + required: true + type: choice + options: + - minor + - patch + +jobs: + bump-version: + permissions: + id-token: write + pull-requests: write + contents: write + + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Configure gitsign + uses: chainguard-dev/actions/setup-gitsign@main + + - name: Install cargo-release + uses: taiki-e/install-action@v1 + with: + tool: cargo-release + + - name: Install sd + uses: taiki-e/install-action@v1 + with: + tool: sd + + - name: Install npm + uses: actions/setup-node@v4 + + - name: Install doctoc + run: npm install doctoc + + - name: Bump version + run: | + cargo release version ${{ inputs.level }} --execute --no-confirm + + - name: Extract version + run: | + echo "version=$(cargo pkgid -p bindgen | cut -d '#' -f 2)" >> $GITHUB_ENV + + - name: Update changelog + run: | + sd "# Unreleased" "# Unreleased\n## Added\n## Changed\n## Removed\n## Fixed\n## Security\n\n# ${{ env.version }} ($(date -I))" CHANGELOG.md + ./node_modules/doctoc/doctoc.js CHANGELOG.md + + - name: Create PR + uses: peter-evans/create-pull-request@v5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + branch: bump-version/${{ env.version }} + base: main + commit-message: "Bump crates version to ${{ env.version }}" + title: "Bump crates version to ${{ env.version }}" + body: | + This pull request was created automatically by GitHub Actions. diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml new file mode 100644 index 0000000000..f636991c38 --- /dev/null +++ b/.github/workflows/create-tag.yml @@ -0,0 +1,49 @@ +name: Create tag for release + +on: + pull_request: + types: + - closed + workflow_dispatch: + inputs: + commit: + description: 'Commit hash' + required: true + type: string +jobs: + create-tag: + if: >- + (inputs.commit || false) || + (github.event.pull_request.merged == true && + github.event.pull_request.user.login == 'github-actions' && + github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && + startsWith(github.event.pull_request.head.ref, 'bump-version') ) + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Compute the commit + run: | + if [[ -z "${{ inputs.commit }}" ]]; then + COMMIT=$(git rev-parse ${{ github.sha }}^@ | grep -Fvx ${{ github.event.pull_request.head.sha }}) + else + COMMIT="${{ inputs.commit }}" + fi + echo "commit=$COMMIT" >> $GITHUB_ENV + + - name: Install rust toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Extract version + run: | + echo "version=$(cargo pkgid -p bindgen | cut -d '#' -f 2)" >> $GITHUB_ENV + + - name: Create tag + uses: mathieudutour/github-tag-action@v6.2 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + commit_sha: ${{ env.commit }} + custom_tag: ${{ env.version }} diff --git a/.github/workflows/deploy-book.yml b/.github/workflows/deploy-book.yml index 9bb1e1b852..7b8cacc55d 100644 --- a/.github/workflows/deploy-book.yml +++ b/.github/workflows/deploy-book.yml @@ -9,13 +9,13 @@ jobs: deploy-book: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: persist-credentials: false - name: Test book run: | - curl -L https://github.com/rust-lang/mdBook/releases/download/v0.4.5/mdbook-v0.4.5-x86_64-unknown-linux-gnu.tar.gz | tar xz + curl -L https://github.com/rust-lang/mdBook/releases/download/v0.4.34/mdbook-v0.4.34-x86_64-unknown-linux-gnu.tar.gz | tar xz ./mdbook build book ./mdbook test book diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index f79ce1036b..d8602f9ad9 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,16 +1,22 @@ -# To trigger this: -# - go to Actions > Publish -# - click the Run Workflow dropdown in the top-right -name: Publish -on: workflow_dispatch +# This is triggered after the Release workflow successfully completes its run +name: Publish on crates.io +on: + workflow_run: + workflows: + - Release + types: + - completed env: CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} jobs: cargo-publish: runs-on: ubuntu-latest + if: ${{ !github.event.pull_request && (github.event.workflow_run.conclusion == 'success') && (github.event.workflow.name == 'Release') }} steps: + - name: Print workflow event name + run: echo "${{ github.event.workflow.name }}" - name: Checkout sources - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install stable toolchain uses: dtolnay/rust-toolchain@master with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7997a9c1b7..5df0c7b1c1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,6 @@ -# Copyright 2022-2023, axodotdev +# This file was autogenerated by cargo-dist: https://opensource.axo.dev/cargo-dist/ +# +# Copyright 2022-2024, axodotdev # SPDX-License-Identifier: MIT or Apache-2.0 # # CI that: @@ -6,14 +8,14 @@ # * checks for a Git Tag that looks like a release # * builds artifacts with cargo-dist (archives, installers, hashes) # * uploads those artifacts to temporary workflow zip -# * on success, uploads the artifacts to a Github Release™ +# * on success, uploads the artifacts to a GitHub Release # -# Note that the Github Release™ will be created with a generated +# Note that the GitHub Release will be created with a generated # title/body based on your changelogs. -name: Release +name: Release permissions: - contents: write + "contents": "write" # This task will run whenever you push a git tag that looks like a version # like "1.0.0", "v0.1.0-prerelease.1", "my-app/0.1.0", "releases/v1.0.0", etc. @@ -21,31 +23,31 @@ permissions: # PACKAGE_NAME must be the name of a Cargo package in your workspace, and VERSION # must be a Cargo-style SemVer Version (must have at least major.minor.patch). # -# If PACKAGE_NAME is specified, then the release will be for that +# If PACKAGE_NAME is specified, then the announcement will be for that # package (erroring out if it doesn't have the given version or isn't cargo-dist-able). # -# If PACKAGE_NAME isn't specified, then the release will be for all +# If PACKAGE_NAME isn't specified, then the announcement will be for all # (cargo-dist-able) packages in the workspace with that version (this mode is # intended for workspaces with only one dist-able package, or with all dist-able # packages versioned/released in lockstep). # # If you push multiple tags at once, separate instances of this workflow will -# spin up, creating an independent Github Release™ for each one. However Github +# spin up, creating an independent announcement for each one. However, GitHub # will hard limit this to 3 tags per commit, as it will assume more tags is a # mistake. # -# If there's a prerelease-style suffix to the version, then the Github Release™ +# If there's a prerelease-style suffix to the version, then the release(s) # will be marked as a prerelease. on: + pull_request: push: tags: - '**[0-9]+.[0-9]+.[0-9]+*' - pull_request: jobs: - # Run 'cargo dist plan' to determine what tasks we need to do + # Run 'cargo dist plan' (or host) to determine what tasks we need to do plan: - runs-on: ubuntu-latest + runs-on: "ubuntu-20.04" outputs: val: ${{ steps.plan.outputs.manifest }} tag: ${{ !github.event.pull_request && github.ref_name || '' }} @@ -58,24 +60,39 @@ jobs: with: submodules: recursive - name: Install cargo-dist - run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.3.1/cargo-dist-installer.sh | sh" + # we specify bash to get pipefail; it guards against the `curl` command + # failing. otherwise `sh` won't catch that `curl` returned non-0 + shell: bash + run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.22.1/cargo-dist-installer.sh | sh" + - name: Cache cargo-dist + uses: actions/upload-artifact@v4 + with: + name: cargo-dist-cache + path: ~/.cargo/bin/cargo-dist + # sure would be cool if github gave us proper conditionals... + # so here's a doubly-nested ternary-via-truthiness to try to provide the best possible + # functionality based on whether this is a pull_request, and whether it's from a fork. + # (PRs run on the *source* but secrets are usually on the *target* -- that's *good* + # but also really annoying to build CI around when it needs secrets to work right.) - id: plan run: | - cargo dist plan ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }} --output-format=json > dist-manifest.json - echo "cargo dist plan ran successfully" - cat dist-manifest.json - echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT" + cargo dist ${{ (!github.event.pull_request && format('host --steps=create --tag={0}', github.ref_name)) || 'plan' }} --output-format=json > plan-dist-manifest.json + echo "cargo dist ran successfully" + cat plan-dist-manifest.json + echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT" - name: "Upload dist-manifest.json" - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: artifacts - path: dist-manifest.json + name: artifacts-plan-dist-manifest + path: plan-dist-manifest.json # Build and packages all the platform-specific things - upload-local-artifacts: + build-local-artifacts: + name: build-local-artifacts (${{ join(matrix.targets, ', ') }}) # Let the initial task tell us to not run (currently very blunt) - needs: plan - if: ${{ fromJson(needs.plan.outputs.val).releases != null && (needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload') }} + needs: + - plan + if: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix.include != null && (needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload') }} strategy: fail-fast: false # Target platforms/runners are computed by cargo-dist in create-release. @@ -92,17 +109,30 @@ jobs: runs-on: ${{ matrix.runner }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json steps: + - name: enable windows longpaths + run: | + git config --global core.longpaths true - uses: actions/checkout@v4 with: submodules: recursive - - uses: swatinem/rust-cache@v2 - name: Install cargo-dist run: ${{ matrix.install_dist }} + # Get the dist-manifest + - name: Fetch local artifacts + uses: actions/download-artifact@v4 + with: + pattern: artifacts-* + path: target/distrib/ + merge-multiple: true + - name: Install dependencies + run: | + ${{ matrix.packages_install }} - name: Build artifacts run: | # Actually do builds and make zips and whatnot - cargo dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json ${{ matrix.dist_args }} > dist-manifest.json + cargo dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json echo "cargo dist ran successfully" - id: cargo-dist name: Post-build @@ -111,81 +141,143 @@ jobs: # inconsistent syntax between shell and powershell. shell: bash run: | - # Parse out what we just built and upload it to the Github Release™ + # Parse out what we just built and upload it to scratch storage echo "paths<> "$GITHUB_OUTPUT" - jq --raw-output ".artifacts[]?.path | select( . != null )" dist-manifest.json >> "$GITHUB_OUTPUT" + jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT" echo "EOF" >> "$GITHUB_OUTPUT" + + cp dist-manifest.json "$BUILD_MANIFEST_NAME" - name: "Upload artifacts" - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: artifacts - path: ${{ steps.cargo-dist.outputs.paths }} + name: artifacts-build-local-${{ join(matrix.targets, '_') }} + path: | + ${{ steps.cargo-dist.outputs.paths }} + ${{ env.BUILD_MANIFEST_NAME }} # Build and package all the platform-agnostic(ish) things - upload-global-artifacts: - needs: [plan, upload-local-artifacts] + build-global-artifacts: + needs: + - plan + - build-local-artifacts runs-on: "ubuntu-20.04" env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json steps: - uses: actions/checkout@v4 with: submodules: recursive - - name: Install cargo-dist - run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.3.1/cargo-dist-installer.sh | sh" + - name: Install cached cargo-dist + uses: actions/download-artifact@v4 + with: + name: cargo-dist-cache + path: ~/.cargo/bin/ + - run: chmod +x ~/.cargo/bin/cargo-dist # Get all the local artifacts for the global tasks to use (for e.g. checksums) - name: Fetch local artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: - name: artifacts + pattern: artifacts-* path: target/distrib/ + merge-multiple: true - id: cargo-dist shell: bash run: | cargo dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json echo "cargo dist ran successfully" - # Parse out what we just built and upload it to the Github Release™ + # Parse out what we just built and upload it to scratch storage echo "paths<> "$GITHUB_OUTPUT" - jq --raw-output ".artifacts[]?.path | select( . != null )" dist-manifest.json >> "$GITHUB_OUTPUT" + jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT" echo "EOF" >> "$GITHUB_OUTPUT" + + cp dist-manifest.json "$BUILD_MANIFEST_NAME" - name: "Upload artifacts" - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: artifacts - path: ${{ steps.cargo-dist.outputs.paths }} - - should-publish: + name: artifacts-build-global + path: | + ${{ steps.cargo-dist.outputs.paths }} + ${{ env.BUILD_MANIFEST_NAME }} + # Determines if we should publish/announce + host: needs: - plan - - upload-local-artifacts - - upload-global-artifacts - if: ${{ needs.plan.outputs.publishing == 'true' }} - runs-on: ubuntu-latest - steps: - - name: print tag - run: echo "ok we're publishing!" - - # Create a Github Release with all the results once everything is done, - publish-release: - needs: [plan, should-publish] - runs-on: ubuntu-latest + - build-local-artifacts + - build-global-artifacts + # Only run if we're "publishing", and only if local and global didn't fail (skipped is fine) + if: ${{ always() && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + runs-on: "ubuntu-20.04" + outputs: + val: ${{ steps.host.outputs.manifest }} steps: - uses: actions/checkout@v4 with: submodules: recursive - - name: "Download artifacts" - uses: actions/download-artifact@v3 + - name: Install cached cargo-dist + uses: actions/download-artifact@v4 + with: + name: cargo-dist-cache + path: ~/.cargo/bin/ + - run: chmod +x ~/.cargo/bin/cargo-dist + # Fetch artifacts from scratch-storage + - name: Fetch artifacts + uses: actions/download-artifact@v4 + with: + pattern: artifacts-* + path: target/distrib/ + merge-multiple: true + - id: host + shell: bash + run: | + cargo dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json + echo "artifacts uploaded and released successfully" + cat dist-manifest.json + echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT" + - name: "Upload dist-manifest.json" + uses: actions/upload-artifact@v4 + with: + # Overwrite the previous copy + name: artifacts-dist-manifest + path: dist-manifest.json + # Create a GitHub Release while uploading all files to it + - name: "Download GitHub Artifacts" + uses: actions/download-artifact@v4 with: - name: artifacts + pattern: artifacts-* path: artifacts - - name: Create Release - uses: ncipollo/release-action@v1 - with: - tag: ${{ needs.plan.outputs.tag }} - name: ${{ fromJson(needs.plan.outputs.val).announcement_title }} - body: ${{ fromJson(needs.plan.outputs.val).announcement_github_body }} - prerelease: ${{ fromJson(needs.plan.outputs.val).announcement_is_prerelease }} - artifacts: "artifacts/*" + merge-multiple: true + - name: Cleanup + run: | + # Remove the granular manifests + rm -f artifacts/*-dist-manifest.json + - name: Create GitHub Release + env: + PRERELEASE_FLAG: "${{ fromJson(steps.host.outputs.manifest).announcement_is_prerelease && '--prerelease' || '' }}" + ANNOUNCEMENT_TITLE: "${{ fromJson(steps.host.outputs.manifest).announcement_title }}" + ANNOUNCEMENT_BODY: "${{ fromJson(steps.host.outputs.manifest).announcement_github_body }}" + RELEASE_COMMIT: "${{ github.sha }}" + run: | + # Write and read notes from a file to avoid quoting breaking things + echo "$ANNOUNCEMENT_BODY" > $RUNNER_TEMP/notes.txt + + gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/* + + announce: + needs: + - plan + - host + # use "always() && ..." to allow us to wait for all publish jobs while + # still allowing individual publish jobs to skip themselves (for prereleases). + # "host" however must run to completion, no skipping allowed! + if: ${{ always() && needs.host.result == 'success' }} + runs-on: "ubuntu-20.04" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive diff --git a/CHANGELOG.md b/CHANGELOG.md index 95b7ac2966..b7ca9f2124 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,196 +7,215 @@ - [Removed](#removed) - [Fixed](#fixed) - [Security](#security) -- [0.69.4 (2024-02-04)](#0694-2024-02-04) +- [v0.71.1 (2024-12-09)](#v0711-2024-12-09) + - [Fixed](#fixed-1) +- [0.71.0 (2024-12-06)](#0710-2024-12-06) - [Added](#added-1) - [Changed](#changed-1) - [Removed](#removed-1) - - [Fixed](#fixed-1) - - [Security](#security-1) -- [0.69.3 (2024-02-04)](#0693-2024-02-04) + - [Fixed](#fixed-2) +- [0.70.1 (2024-08-20)](#0701-2024-08-20) - [Added](#added-2) - [Changed](#changed-2) - [Removed](#removed-2) - - [Fixed](#fixed-2) - - [Security](#security-2) -- [0.69.2 (2024-01-13)](#0692-2024-01-13) + - [Fixed](#fixed-3) + - [Security](#security-1) +- [0.70.0 (2024-08-16)](#0700-2024-08-16) - [Added](#added-3) - [Changed](#changed-3) - [Removed](#removed-3) - - [Fixed](#fixed-3) - - [Security](#security-3) -- [0.69.1 (2023-11-02)](#0691-2023-11-02) - [Fixed](#fixed-4) -- [0.69.0 (2023-11-01)](#0690-2023-11-01) + - [Security](#security-2) +- [0.69.4 (2024-02-04)](#0694-2024-02-04) - [Added](#added-4) - [Changed](#changed-4) - [Removed](#removed-4) - [Fixed](#fixed-5) - - [Security](#security-4) -- [0.68.1](#0681) - - [Fixed](#fixed-6) -- [0.68.0](#0680) + - [Security](#security-3) +- [0.69.3 (2024-02-04)](#0693-2024-02-04) - [Added](#added-5) - [Changed](#changed-5) - [Removed](#removed-5) - - [Fixed](#fixed-7) -- [0.67.0](#0670) -- [0.66.1](#0661) - - [Removed](#removed-6) -- [0.66.0](#0660) + - [Fixed](#fixed-6) + - [Security](#security-4) +- [0.69.2 (2024-01-13)](#0692-2024-01-13) - [Added](#added-6) - [Changed](#changed-6) - - [Removed](#removed-7) -- [0.65.1](#0651) + - [Removed](#removed-6) + - [Fixed](#fixed-7) + - [Security](#security-5) +- [0.69.1 (2023-11-02)](#0691-2023-11-02) - [Fixed](#fixed-8) -- [0.65.0](#0650) +- [0.69.0 (2023-11-01)](#0690-2023-11-01) - [Added](#added-7) - [Changed](#changed-7) - - [Removed](#removed-8) -- [0.64.0](#0640) + - [Removed](#removed-7) + - [Fixed](#fixed-9) + - [Security](#security-6) +- [0.68.1](#0681) + - [Fixed](#fixed-10) +- [0.68.0](#0680) - [Added](#added-8) - [Changed](#changed-8) -- [0.63.0](#0630) + - [Removed](#removed-8) + - [Fixed](#fixed-11) +- [0.67.0](#0670) +- [0.66.1](#0661) + - [Removed](#removed-9) +- [0.66.0](#0660) - [Added](#added-9) - [Changed](#changed-9) - - [Removed](#removed-9) -- [0.62.0](#0620) + - [Removed](#removed-10) +- [0.65.1](#0651) + - [Fixed](#fixed-12) +- [0.65.0](#0650) - [Added](#added-10) - [Changed](#changed-10) - - [Fixed](#fixed-9) -- [0.61.0](#0610) + - [Removed](#removed-11) +- [0.64.0](#0640) - [Added](#added-11) - [Changed](#changed-11) - - [Fixed](#fixed-10) -- [0.60.1](#0601) - - [Fixed](#fixed-11) -- [0.60.0](#0600) +- [0.63.0](#0630) - [Added](#added-12) - - [Fixed](#fixed-12) - [Changed](#changed-12) - - [Removed](#removed-10) -- [0.59.2](#0592) -- [0.59.1](#0591) - - [Fixed](#fixed-13) -- [0.59.0](#0590) + - [Removed](#removed-12) +- [0.62.0](#0620) - [Added](#added-13) - - [Fixed](#fixed-14) - [Changed](#changed-13) -- [0.58.1](#0581) + - [Fixed](#fixed-13) +- [0.61.0](#0610) - [Added](#added-14) -- [0.58.0](#0580) - - [Added](#added-15) - - [Fixed](#fixed-15) - [Changed](#changed-14) - - [Deprecated](#deprecated) - - [Removed](#removed-11) + - [Fixed](#fixed-14) +- [0.60.1](#0601) + - [Fixed](#fixed-15) +- [0.60.0](#0600) + - [Added](#added-15) - [Fixed](#fixed-16) - - [Security](#security-5) -- [0.57.0](#0570) - - [Added](#added-16) - - [Fixed](#fixed-17) -- [0.56.0](#0560) - - [Added](#added-17) - [Changed](#changed-15) + - [Removed](#removed-13) +- [0.59.2](#0592) +- [0.59.1](#0591) + - [Fixed](#fixed-17) +- [0.59.0](#0590) + - [Added](#added-16) - [Fixed](#fixed-18) -- [0.55.1](#0551) - - [Fixed](#fixed-19) -- [0.55.0](#0550) - - [Removed](#removed-12) - - [Added](#added-18) - [Changed](#changed-16) +- [0.58.1](#0581) + - [Added](#added-17) +- [0.58.0](#0580) + - [Added](#added-18) + - [Fixed](#fixed-19) + - [Changed](#changed-17) + - [Deprecated](#deprecated) + - [Removed](#removed-14) - [Fixed](#fixed-20) -- [0.54.1](#0541) + - [Security](#security-7) +- [0.57.0](#0570) - [Added](#added-19) - - [Changed](#changed-17) - [Fixed](#fixed-21) -- [0.54.0](#0540) +- [0.56.0](#0560) - [Added](#added-20) - [Changed](#changed-18) - [Fixed](#fixed-22) -- [0.53.3](#0533) - - [Added](#added-21) +- [0.55.1](#0551) - [Fixed](#fixed-23) -- [0.53.2](#0532) +- [0.55.0](#0550) + - [Removed](#removed-15) + - [Added](#added-21) - [Changed](#changed-19) -- [0.53.1](#0531) + - [Fixed](#fixed-24) +- [0.54.1](#0541) - [Added](#added-22) -- [0.53.0](#0530) - - [Added](#added-23) - [Changed](#changed-20) - - [Fixed](#fixed-24) -- [0.52.0](#0520) - - [Added](#added-24) - - [Changed](#changed-21) - [Fixed](#fixed-25) -- [0.51.1](#0511) +- [0.54.0](#0540) + - [Added](#added-23) + - [Changed](#changed-21) - [Fixed](#fixed-26) - - [Changed](#changed-22) -- [0.51.0](#0510) +- [0.53.3](#0533) + - [Added](#added-24) - [Fixed](#fixed-27) - - [Changed](#changed-23) +- [0.53.2](#0532) + - [Changed](#changed-22) +- [0.53.1](#0531) - [Added](#added-25) -- [0.50.0](#0500) +- [0.53.0](#0530) - [Added](#added-26) -- [0.49.3](#0493) + - [Changed](#changed-23) + - [Fixed](#fixed-28) +- [0.52.0](#0520) - [Added](#added-27) -- [0.49.2](#0492) - [Changed](#changed-24) -- [0.49.1](#0491) - - [Fixed](#fixed-28) - - [Changed](#changed-25) -- [0.49.0](#0490) - - [Added](#added-28) - [Fixed](#fixed-29) +- [0.51.1](#0511) + - [Fixed](#fixed-30) + - [Changed](#changed-25) +- [0.51.0](#0510) + - [Fixed](#fixed-31) - [Changed](#changed-26) + - [Added](#added-28) +- [0.50.0](#0500) + - [Added](#added-29) +- [0.49.3](#0493) + - [Added](#added-30) +- [0.49.2](#0492) + - [Changed](#changed-27) +- [0.49.1](#0491) + - [Fixed](#fixed-32) + - [Changed](#changed-28) +- [0.49.0](#0490) + - [Added](#added-31) + - [Fixed](#fixed-33) + - [Changed](#changed-29) - [0.48.1](#0481) - - [Fixed](#fixed-30) + - [Fixed](#fixed-34) - [0.48.0](#0480) - - [Changed](#changed-27) - - [Fixed](#fixed-31) + - [Changed](#changed-30) + - [Fixed](#fixed-35) - [0.47.4](#0474) - - [Added](#added-29) + - [Added](#added-32) - [0.47.3](#0473) - - [Changed](#changed-28) + - [Changed](#changed-31) - [0.47.2](#0472) - - [Fixed](#fixed-32) + - [Fixed](#fixed-36) - [0.47.1](#0471) - - [Changed](#changed-29) - - [Fixed](#fixed-33) + - [Changed](#changed-32) + - [Fixed](#fixed-37) - [0.47.0](#0470) - - [Changed](#changed-30) - - [Fixed](#fixed-34) + - [Changed](#changed-33) + - [Fixed](#fixed-38) - [0.33.1 .. 0.46.0](#0331--0460) - - [Added](#added-30) - - [Removed](#removed-13) - - [Changed](#changed-31) - - [Fixed](#fixed-35) + - [Added](#added-33) + - [Removed](#removed-16) + - [Changed](#changed-34) + - [Fixed](#fixed-39) - [0.33.1](#0331) - - [Fixed](#fixed-36) + - [Fixed](#fixed-40) - [0.33.0](#0330) - [0.32.2](#0322) - - [Fixed](#fixed-37) + - [Fixed](#fixed-41) - [0.32.1](#0321) - - [Fixed](#fixed-38) + - [Fixed](#fixed-42) - [0.32.0](#0320) - - [Added](#added-31) - - [Changed](#changed-32) - - [Fixed](#fixed-39) + - [Added](#added-34) + - [Changed](#changed-35) + - [Fixed](#fixed-43) - [0.31.0](#0310) - - [Added](#added-32) - - [Changed](#changed-33) + - [Added](#added-35) + - [Changed](#changed-36) - [Deprecated](#deprecated-1) - - [Removed](#removed-14) - - [Fixed](#fixed-40) + - [Removed](#removed-17) + - [Fixed](#fixed-44) - [0.30.0](#0300) - - [Added](#added-33) - - [Changed](#changed-34) + - [Added](#added-36) + - [Changed](#changed-37) - [Deprecated](#deprecated-2) - - [Fixed](#fixed-41) + - [Fixed](#fixed-45) - [0.29.0](#0290) - - [Added](#added-34) - - [Changed](#changed-35) - - [Fixed](#fixed-42) + - [Added](#added-37) + - [Changed](#changed-38) + - [Fixed](#fixed-46) @@ -204,10 +223,67 @@ # Unreleased ## Added ## Changed +## Removed +## Fixed +## Security + +# v0.71.1 (2024-12-09) +## Fixed +- Fix `--version` and `--generate-shell-completions` (#3040) + +# 0.71.0 (2024-12-06) +## Added +- Add the `ParseCallbacks::new_item_found` callback to expose the original and final name of structs, unions and enums (#2658). +- Add the `field_type_name` field to `FieldInfo` to expose the name of the type of a field (#2863) +- Add support for custom attributes with the `--with-attribute-custom` flag (#2866) +- Allow setting `--rust-target` to any Rust version supported by bindgen (#2993) +- Use c-string literals if the `--generate-cstr` flag is used for Rust targets after 1.77 under the 2021 edition (#2996) +- Add the `--rust-edition` flag which allows to select which Rust edition to target. (#3002, #3013) +- Use `unsafe extern` instead of `extern` in blocks for any Rust target after 1.82. (#3015) +## Changed +- The `--wrap-static-fns` related options no longer require the experimental feature or flag (#2928) +- Use the `Display` implementation instead of the `Debug` one for `BindgenError` in `bindgen-cli` (#3005) +## Removed +- Dropped support for any Clang versions strictly lower than 9.0 (#2932) +- Dropped support for any Rust version strictly lower than 1.33 (#2993) +## Fixed +- Represent opaque types in a FFI-safe way (#2880) +- Use the underlying type of any atomic type instead of panicking (#2920) +- Use the right characters for newlines on windows (#2923) +- Inlined namespaces are properly recognized now (#2950) +- Unsafe calls to `libloading` are now wrapped in `unsafe` blocks when using dynamic loading (#2961) +- The `ParseCallbacks::field_visibility` callback is now called for newtypes as well (#2967) +- Gate the use of the `addr_of` and `addr_of_mut` macros under the 1.51 rust version (#2988) + +# 0.70.1 (2024-08-20) +## Added +## Changed +## Removed +## Fixed +- Fix regression where the `const` layout tests were triggering the `unnecessary_operation` and `identity_op` clippy warnings. +## Security + +# 0.70.0 (2024-08-16) +## Added - Add target mappings for riscv64imac and riscv32imafc. +- Add a complex macro fallback API (#2779). +- Add option to use DST structs for flexible arrays (--flexarray-dst, #2772). +- Add option to dynamically load variables (#2812). +- Add option in CLI to use rustified non-exhaustive enums (--rustified-non-exhaustive-enum, #2847). +- Add field_type_name to FieldInfo. +## Changed +- Remove which and lazy-static dependencies (#2809, #2817). +- Generate compile-time layout tests (#2787). +- Print `bindgen-cli` errors to stderr instead of stdout (#2840) ## Removed ## Fixed +- Fix `--formatter=prettyplease` not working in `bindgen-cli` by adding `prettyplease` feature and + enabling it by default for `bindgen-cli` (#2789) . +- Fix `--allowlist-item` so anonymous enums are no longer ignored (#2827). +- Use clang_getFileLocation instead of clang_getSpellingLocation to fix clang-trunk (#2824). +- Fix generated constants: `f64::INFINITY`, `f64::NEG_ INFINITY`, `f64::NAN` (#2854). ## Security +- Update `tempfile` and `rustix` due to [GHSA-c827-hfw6-qwvm](https://github.com/advisories/GHSA-c827-hfw6-qwvm). # 0.69.4 (2024-02-04) ## Added @@ -437,7 +513,7 @@ This version was skipped due to some problems on the release workflow. * The `ParseCallbacks::generated_name_override` method now receives `ItemInfo<'_>` as argument instead of a `&str`. * Updated the `clang-sys` crate version to 1.4.0 to support clang 15. - * The return type is now ommited in signatures of functions returning `void`. + * The return type is now omitted in signatures of functions returning `void`. * Updated the `clap` dependency for `bindgen-cli` to 4. * Rewrote the `bindgen-cli` argument parser which could introduce unexpected behavior changes. @@ -1474,7 +1550,7 @@ Released 2017/10/27 We <3 folks who [help us find and fix issues via fuzzing][fuzzing]! *hint hint* -* Added experimental support for the `thiscall` ABI when targetting Rust +* Added experimental support for the `thiscall` ABI when targeting Rust nightly. [#1065][] ## Changed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 491e233147..9c28e198c9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,7 +37,9 @@ and introduce yourself. - [Updating the changelog](#updating-the-changelog) - [Merge to `main`](#merge-to-main) - [Tag and publish](#tag-and-publish) - - [Create a new release on GitHub](create-a-new-relese-on-github) + - [Create a new release on Github](#create-a-new-release-on-github) + - [What to do if a Github release fails](#what-to-do-if-a-github-release-fails) + - [Create a new crates.io release](#create-a-new-cratesio-release) @@ -52,18 +54,18 @@ We abide by the [Rust Code of Conduct][coc] and ask that you do as well. Think you've found a bug? File an issue! To help us understand and reproduce the issue, provide us with: -* A (preferably reduced) C/C++ header file that reproduces the issue -* The `bindgen` flags used to reproduce the issue with the header file -* The expected `bindgen` output -* The actual `bindgen` output -* The [debugging logs](#debug-logging) generated when running `bindgen` on this testcase +- A (preferably reduced) C/C++ header file that reproduces the issue +- The `bindgen` flags used to reproduce the issue with the header file +- The expected `bindgen` output +- The actual `bindgen` output +- The [debugging logs](#debug-logging) generated when running `bindgen` on this testcase ## Looking to Start Contributing to `bindgen`? -* [Issues labeled "easy"](https://github.com/rust-lang/rust-bindgen/issues?q=is%3Aopen+is%3Aissue+label%3AE-easy) -* [Issues labeled "less easy"](https://github.com/rust-lang/rust-bindgen/issues?q=is%3Aopen+is%3Aissue+label%3AE-less-easy) -* [Issues labeled "help wanted"](https://github.com/rust-lang/rust-bindgen/labels/help%20wanted) -* Still can't find something to work on? [Drop a comment here](https://github.com/rust-lang/rust-bindgen/issues/747) +- [Issues labeled "easy"](https://github.com/rust-lang/rust-bindgen/issues?q=is%3Aopen+is%3Aissue+label%3AE-easy) +- [Issues labeled "less easy"](https://github.com/rust-lang/rust-bindgen/issues?q=is%3Aopen+is%3Aissue+label%3AE-less-easy) +- [Issues labeled "help wanted"](https://github.com/rust-lang/rust-bindgen/labels/help%20wanted) +- Still can't find something to work on? [Drop a comment here](https://github.com/rust-lang/rust-bindgen/issues/747) ## Prerequisites @@ -80,16 +82,16 @@ To check via command line, you can run `cargo +nightly fmt --check`. To build the `bindgen` library and the `bindgen` executable: -``` -$ cargo build +```sh +cargo build ``` If you installed multiple versions of llvm, it may not be able to locate the -latest version of libclang. In that case, you may want to either uninstall other -versions of llvm, or specify the path of the desired libclang explicitly: +latest version of `libclang`. In that case, you may want to either uninstall other +versions of llvm, or specify the path of the desired `libclang` explicitly: -``` -$ export LIBCLANG_PATH=path/to/clang-9.0/lib +```sh +export LIBCLANG_PATH=path/to/clang-9.0/lib ``` ## Testing @@ -105,7 +107,7 @@ There are also some integration tests in the `./bindgen-integration` crate, whic generate bindings to some C++ code, and then uses the bindings, asserting that values are what we expect them to be, both on the Rust and C++ side. -The generated and expected bindings are formatted with [prettyplease] before they are +The generated and expected bindings are formatted with [`prettyplease`] before they are compared. It is a default (but optional) dependency of `bindgen`, so be sure to keep that in mind (if you built `bindgen` with the `--no-default-features` option of Cargo). @@ -116,14 +118,13 @@ Note: running `cargo test` from the root directory of `bindgen`'s repository doe automatically test the generated bindings or run the integration tests. These steps must be performed manually when needed. - ### Testing Bindings Generation To regenerate bindings from the corpus of test headers in `bindgen-tests/tests/headers` and compare them against the expected bindings in `bindgen-tests/tests/expectations/tests`, run: -``` -$ cargo test +```sh +cargo test ``` As long as you aren't making any changes to `bindgen`'s output, running this @@ -132,12 +133,12 @@ should be sufficient to test your local modifications. You may set the `BINDGEN_OVERWRITE_EXPECTED` environment variable to overwrite the expected bindings with `bindgen`'s current output: -``` -$ BINDGEN_OVERWRITE_EXPECTED=1 cargo test +```sh +BINDGEN_OVERWRITE_EXPECTED=1 cargo test ``` -If you set the BINDGEN_TESTS_DIFFTOOL environment variable, `cargo test` will -execute $BINDGEN_TESTS_DIFFTOOL /path/of/expected/output /path/of/actual/output +If you set the `BINDGEN_TESTS_DIFFTOOL` environment variable, `cargo test` will +execute `BINDGEN_TESTS_DIFFTOOL /path/of/expected/output /path/of/actual/output` when the expected output differs from the actual output. You can use this to hand check differences by setting it to e.g. "meld" (assuming you have meld installed). @@ -155,14 +156,14 @@ pass. Also, run the integration tests (see below). You can do this with these commands: -``` -$ cd bindgen-tests/tests/expectations -$ cargo test +```sh +cd bindgen-tests/tests/expectations +cargo test ``` ### Testing a Single Header's Bindings Generation and Compiling its Bindings -Note: You will need to install [Graphviz](https://graphviz.org/) since that +Note: You will need to install [graphviz](https://graphviz.org/) since that is a dependency for running `test-one.sh`. Sometimes it's useful to work with one test header from start (generating @@ -171,8 +172,8 @@ tests). This can be done with the `bindgen-tests/tests/test-one.sh` script. It s searching for test headers. For example, to test `tests/headers/what_is_going_on.hpp`, execute this command: -``` -$ ./bindgen-tests/tests/test-one.sh going +```sh +./bindgen-tests/tests/test-one.sh going ``` Note that `test-one.sh` does not recompile `bindgen`, so if you change the code, @@ -195,9 +196,9 @@ specify them at the top of the test header, with a comment like this: Then verify the new Rust bindings compile and pass their layout tests: -``` -$ cd bindgen-tests/tests/expectations -$ cargo test new_test_header +```sh +cd bindgen-tests/tests/expectations +cargo test new_test_header ``` ### Test Expectations and `libclang` Versions @@ -208,8 +209,8 @@ can add multiple test expectations, one for each supported `libclang` version. Instead of having a single `bindgen-tests/tests/expectations/tests/my_test.rs` file, add each of: -* `bindgen-tests/tests/expectations/tests/libclang-16/my_test.rs` -* `bindgen-tests/tests/expectations/tests/libclang-9/my_test.rs` +- `bindgen-tests/tests/expectations/tests/libclang-16/my_test.rs` +- `bindgen-tests/tests/expectations/tests/libclang-9/my_test.rs` If you need to update the test expectations for a test file that generates different bindings for different `libclang` versions, you *don't* need to have @@ -222,8 +223,8 @@ Usually, `bindgen`'s test runner can infer which version of `libclang` you have. If for some reason it can't, you can force a specific `libclang` version to check the bindings against with a cargo feature: -``` -$ cargo test --features __testing_only_libclang_$VERSION +```sh +cargo test --features __testing_only_libclang_$VERSION ``` depending on which version of `libclang` you have installed. @@ -236,9 +237,9 @@ values are what we expect them to be, both on the Rust and C++ side. To run the integration tests, issue the following: -``` -$ cd bindgen-integration -$ cargo test +```sh +cd bindgen-integration +cargo test ``` ### Fuzzing `bindgen` with `csmith` @@ -255,7 +256,7 @@ The `tests/quickchecking` crate generates property tests for `bindgen`. From the crate's directory you can run the tests with `cargo run`. For details on additional configuration including how to preserve / inspect the generated property tests, see -[./tests/quickchecking/README.md](./tests/quickchecking/README.md). +[`./tests/quickchecking/README.md`](./tests/quickchecking/README.md). ## Code Overview @@ -272,39 +273,39 @@ The umbrella IR type is the `Item`. It contains various nested `enum`s that let us drill down and get more specific about the kind of construct that we're looking at. Here is a summary of the IR types and their relationships: -* `Item` contains: - * An `ItemId` to uniquely identify it. - * An `ItemKind`, which is one of: - * A `Module`, which is originally a C++ namespace and becomes a Rust +- `Item` contains: + - An `ItemId` to uniquely identify it. + - An `ItemKind`, which is one of: + - A `Module`, which is originally a C++ namespace and becomes a Rust module. It contains the set of `ItemId`s of `Item`s that are defined within it. - * A `Type`, which contains: - * A `Layout`, describing the type's size and alignment. - * A `TypeKind`, which is one of: - * Some integer type. - * Some float type. - * A `Pointer` to another type. - * A function pointer type, with `ItemId`s of its parameter types + - A `Type`, which contains: + - A `Layout`, describing the type's size and alignment. + - A `TypeKind`, which is one of: + - Some integer type. + - Some float type. + - A `Pointer` to another type. + - A function pointer type, with `ItemId`s of its parameter types and return type. - * An `Alias` to another type (`typedef` or `using X = ...`). - * A fixed size `Array` of `n` elements of another type. - * A `Comp` compound type, which is either a `struct`, `class`, + - An `Alias` to another type (`typedef` or `using X = ...`). + - A fixed size `Array` of `n` elements of another type. + - A `Comp` compound type, which is either a `struct`, `class`, or `union`. This is potentially a template definition. - * A `TemplateInstantiation` referencing some template definition + - A `TemplateInstantiation` referencing some template definition and a set of template argument types. - * Etc... - * A `Function`, which contains: - * An ABI - * A mangled name - * a `FunctionKind`, which describes whether this function is a plain + - Etc... + - A `Function`, which contains: + - An ABI + - A mangled name + - a `FunctionKind`, which describes whether this function is a plain function, method, static method, constructor, destructor, etc. - * The `ItemId` of its function pointer type. - * A `Var` representing a static variable or `#define` constant, which + - The `ItemId` of its function pointer type. + - A `Var` representing a static variable or `#define` constant, which contains: - * Its type's `ItemId` - * Optionally, a mangled name - * Optionally, a value - * An optional `clang::SourceLocation` that holds the first source code + - Its type's `ItemId` + - Optionally, a mangled name + - Optionally, a value + - An optional `clang::SourceLocation` that holds the first source code location where the `Item` was encountered. The IR forms a graph of interconnected and inter-referencing types and @@ -321,8 +322,8 @@ parameters a given type uses. The analyses are defined in `ir::analysis::MonotoneFramework` trait. The final phase is generating Rust source text from the analyzed IR, and it is -defined in `src/codegen/*`. We use the `quote` crate, which provides the `quote! -{ ... }` macro for quasi-quoting Rust forms. Some options that affect the +defined in `src/codegen/*`. We use the `quote` crate, which provides the `quote!{ ... }` +macro for quasi-quoting Rust forms. Some options that affect the generated Rust code are implemented using the [`syn`](https://docs.rs/syn) crate. ### Implementing new options using `syn` @@ -349,13 +350,13 @@ changes should be squashed into the original commit. Unsure who to ask for review? Ask any of: -* `@emilio` -* `@pvdrz` +- `@emilio` +- `@pvdrz` More resources: -* [Servo's GitHub Workflow](https://github.com/servo/servo/wiki/Github-workflow) -* [Beginner's Guide to Rebasing and Squashing](https://github.com/servo/servo/wiki/Beginner's-guide-to-rebasing-and-squashing) +- [Servo's GitHub Workflow](https://github.com/servo/servo/wiki/Github-workflow) +- [Beginner's Guide to Rebasing and Squashing](https://github.com/servo/servo/wiki/Beginner's-guide-to-rebasing-and-squashing) ## Generating Graphviz Dot Files @@ -366,22 +367,22 @@ debugging bindgen! First, make sure you have Graphviz and `dot` installed: -``` -$ brew install graphviz # OS X -$ sudo dnf install graphviz # Fedora -$ # Etc... +```sh +brew install graphviz # OS X +sudo dnf install graphviz # Fedora +# Etc... ``` Then, use the `--emit-ir-graphviz` flag to generate a `dot` file from our IR: -``` -$ cargo run -- example.hpp --emit-ir-graphviz output.dot +```sh +cargo run -- example.hpp --emit-ir-graphviz output.dot ``` Finally, convert the `dot` file to an image: -``` -$ dot -Tpng output.dot -o output.png +```sh +dot -Tpng output.dot -o output.png ``` The final result will look something like this: @@ -393,14 +394,14 @@ The final result will look something like this: To help debug what `bindgen` is doing, you can define the environment variable `RUST_LOG=bindgen` to get a bunch of debugging log spew. -``` -$ RUST_LOG=bindgen ./target/debug/bindgen [flags...] ~/path/to/some/header.h +```sh +RUST_LOG=bindgen ./target/debug/bindgen [flags...] ~/path/to/some/header.h ``` This logging can also be used when debugging failing tests: -``` -$ RUST_LOG=bindgen cargo test +```sh +RUST_LOG=bindgen cargo test ``` ## Using `creduce` to Minimize Test Cases @@ -417,13 +418,13 @@ that same bad behavior. Often, you can install `creduce` from your OS's package manager: -``` -$ sudo apt install creduce -$ brew install creduce -$ # Etc... +```sh +sudo apt install creduce +brew install creduce +# Etc... ``` -Otherwise, follow [these instructions](https://github.com/csmith-project/creduce/blob/main/INSTALL.md) for building and/or installing `creduce`. +Otherwise, follow [these instructions](https://github.com/csmith-project/creduce/blob/master/INSTALL.md) for building and/or installing `creduce`. Running `creduce` requires two things: @@ -434,7 +435,9 @@ Running `creduce` requires two things: With those two things in hand, running `creduce` looks like this: - $ creduce ./predicate.sh ./isolated-test-case.h +```sh +creduce ./predicate.sh ./isolated-test-case.h +``` ### Isolating Your Test Case @@ -488,10 +491,11 @@ to fail to compile `bindgen`'s emitted bindings, you can invoke `predicate.py` like this: ```bash +# the rustc-grep argument expects a regex, thus escape where necessary path/to/rust-bindgen/csmith-fuzzing/predicate.py \ --bindings-grep NameOfTheStructThatIsErroneouslyDerivingEq \ --expect-compile-fail \ - --rustc-grep 'error[E0277]: the trait bound `f64: std::cmp::Eq` is not satisfied' \ + --rustc-grep 'error\[E0277\]: the trait bound `f64: std::cmp::Eq` is not satisfied' \ ./isolated-test-case.h ``` @@ -508,8 +512,8 @@ path/to/rust-bindgen/csmith-fuzzing/predicate.py \ For details on all the flags that you can pass to `predicate.py`, run: -``` -$ path/to/rust-bindgen/csmith-fuzzing/predicate.py --help +```sh +path/to/rust-bindgen/csmith-fuzzing/predicate.py --help ``` And you can always write your own, arbitrary predicate script if you prefer. @@ -532,9 +536,9 @@ To cut a release, the following needs to happen: Update the CHANGELOG.md file with the changes from the last release. Something like the following is a useful way to check what has landed: - ``` - $ git log --oneline v0.62.0..HEAD - ``` +```sh +git log --oneline v0.62.0..HEAD +``` Also worth checking the [next-release tag](https://github.com/rust-lang/rust-bindgen/pulls?q=is%3Apr+label%3Anext-release). @@ -551,28 +555,33 @@ important fix) you can skip this. ### Tag and publish Once you're in `main`. Remember to install `doctoc` by running: -``` + +```sh npm install doctoc ``` And then run: -``` + +```sh cargo release [patch|minor] --no-publish --execute ``` This does the following: - Bump the version. -- Turn the `Unreleased` section of the changelog into the section for the version being published. +- Turn the `Unreleased` section of the changelog into the section for the version being released. - Update the table of contents of the changelog using `doctoc`. - Tag (`git tag`) the HEAD commit -- Publish (`cargo publish`) bindgen and bindgen-cli - Push (`git push`) to GitHub The `patch` and `minor` refer to semver concepts: -- `patch` would bump __v0.68.1__ to __v0.68.2__ -- `feature` would bump __v0.68.2__ to __v0.69.0__ +- `patch` would bump **v0.68.1** to **v0.68.2** +- `minor` would bump **v0.68.2** to **v0.69.0** + +> NOTE: +> We use the `--no-publish` so that the crates are only published after the release is complete. +> This is automatic, provided the release CI job is successful. ### Create a new release on Github @@ -587,23 +596,22 @@ a draft GitHub release will be created, to avoid notifying watchers of the repo should a CI step fail. If everything succeeds, -bindgen cli installers for Linux/MacOS and Windows will be created, -as well as tarballs. -See `[workspace.metadata.dist]` section in Cargo.toml for the configuration. +tarballs containing bindgen cli executables for Linux and MacOS +(both for x86 and Arm) will be created. +See `[workspace.metadata.dist]` section in `Cargo.toml` for the configuration. To update the release configuration, -when a new cargo-dist is available: +when a new `cargo-dist` is available: -``` +```sh cargo dist init # from "cargo install cargo-dist" -cargo dist generate-ci # to update .github/workflows/release.yml ``` ### What to do if a Github release fails -If the release process failed after you run `cargo release` you can manually +If the release process fails after you run `cargo release`, you can manually delete the tag and release from Github. Also remember to delete the tag locally -by running `git tag -d`. Once all the extra changes are in the `main` branch +by running `git tag -d`. Once all the extra changes are in the `main` branch, you can trigger a release by creating a new tag using `git tag` and push it using `git push --tag`. @@ -615,4 +623,4 @@ and run a new workflow using the "Run Workflow" button. Remember that crates.io releases cannot be deleted! -[prettyplease]: https://github.com/dtolnay/prettyplease +[`prettyplease`]: https://github.com/dtolnay/prettyplease diff --git a/Cargo.lock b/Cargo.lock index 4fa9dbcf51..4e88c224f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,34 +4,46 @@ version = 3 [[package]] name = "aho-corasick" -version = "0.7.20" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "annotate-snippets" -version = "0.9.1" +version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3b9d411ecbaf79885c6df4d75fff75858d5995ff25385657a28af47e82f9c36" +checksum = "24e35ed54e5ea7997c14ed4c70ba043478db1112e98263b3b035907aa197d991" dependencies = [ + "anstyle", "unicode-width", - "yansi-term", ] +[[package]] +name = "anstyle" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + [[package]] name = "bindgen" -version = "0.69.4" +version = "0.71.1" dependencies = [ "annotate-snippets", "bitflags 2.2.1", "cexpr", "clang-sys", + "clap", + "clap_complete", "itertools", - "lazy_static", - "lazycell", "log", "prettyplease", "proc-macro2", @@ -39,19 +51,17 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.18", - "which", + "syn 2.0.90", ] [[package]] name = "bindgen-cli" -version = "0.69.4" +version = "0.71.1" dependencies = [ "bindgen", - "clap", - "clap_complete", "env_logger 0.10.0", "log", + "proc-macro2", "shlex", ] @@ -68,13 +78,13 @@ name = "bindgen-tests" version = "0.1.0" dependencies = [ "bindgen", - "clap", - "clap_complete", "owo-colors", "prettyplease", + "proc-macro2", + "regex", "shlex", "similar", - "syn 2.0.18", + "syn 2.0.90", "tempfile", ] @@ -98,9 +108,12 @@ checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" [[package]] name = "cc" -version = "1.0.78" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d" +checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc" +dependencies = [ + "shlex", +] [[package]] name = "cexpr" @@ -119,9 +132,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "clang-sys" -version = "1.4.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa2e27ae6ab525c3d369ded447057bca5438d86dc3a68f6faafb8269ba82ebf3" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" dependencies = [ "glob", "libc", @@ -162,7 +175,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 1.0.107", + "syn 1.0.109", ] [[package]] @@ -176,9 +189,9 @@ dependencies = [ [[package]] name = "either" -version = "1.8.1" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "env_logger" @@ -205,39 +218,28 @@ dependencies = [ [[package]] name = "errno" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" -dependencies = [ - "errno-dragonfly", - "libc", - "windows-sys 0.48.0", -] - -[[package]] -name = "errno-dragonfly" -version = "0.1.2" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" dependencies = [ - "cc", "libc", + "windows-sys 0.52.0", ] [[package]] name = "fastrand" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" dependencies = [ "instant", ] [[package]] name = "getrandom" -version = "0.2.8" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", @@ -252,15 +254,21 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "heck" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hermit-abi" -version = "0.3.2" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" [[package]] name = "humantime" @@ -279,69 +287,51 @@ dependencies = [ [[package]] name = "io-lifetimes" -version = "1.0.4" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7d6c6f8c91b4b9ed43484ad1a938e393caf35960fce7f82a040497207bd8e9e" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ + "hermit-abi 0.3.9", "libc", - "windows-sys 0.42.0", + "windows-sys 0.48.0", ] [[package]] name = "is-terminal" -version = "0.4.7" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f" +checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" dependencies = [ - "hermit-abi", - "io-lifetimes", - "rustix 0.37.3", - "windows-sys 0.48.0", + "hermit-abi 0.4.0", + "libc", + "windows-sys 0.52.0", ] [[package]] name = "itertools" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ "either", ] -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - [[package]] name = "libc" -version = "0.2.139" +version = "0.2.167" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" +checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc" [[package]] name = "libloading" -version = "0.7.4" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" dependencies = [ "cfg-if", - "winapi", + "windows-targets 0.52.6", ] -[[package]] -name = "linux-raw-sys" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f051f77a7c8e6957c0696eac88f26b0117e54f52d3fc682ab19397a8812846a4" - [[package]] name = "linux-raw-sys" version = "0.3.8" @@ -350,12 +340,9 @@ checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" [[package]] name = "log" -version = "0.4.17" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" -dependencies = [ - "cfg-if", -] +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "malloc_buf" @@ -368,9 +355,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.5.0" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "minimal-lexical" @@ -399,9 +386,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.17.0" +version = "1.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66" +checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" [[package]] name = "os_str_bytes" @@ -411,18 +398,18 @@ checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee" [[package]] name = "owo-colors" -version = "3.5.0" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" +checksum = "fb37767f6569cd834a413442455e0f066d0d522de8630436e2a1761d9726ba56" [[package]] name = "prettyplease" -version = "0.2.7" +version = "0.2.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43ded2b5b204571f065ab8540367d738dfe1b3606ab9eb669dcfb5e7a3a07501" +checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033" dependencies = [ "proc-macro2", - "syn 2.0.18", + "syn 2.0.90", ] [[package]] @@ -434,7 +421,7 @@ dependencies = [ "proc-macro-error-attr", "proc-macro2", "quote", - "syn 1.0.107", + "syn 1.0.109", "version_check", ] @@ -451,9 +438,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.60" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] @@ -474,16 +461,15 @@ name = "quickchecking" version = "0.0.0" dependencies = [ "clap", - "lazy_static", "quickcheck", "tempfile", ] [[package]] name = "quote" -version = "1.0.28" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] @@ -508,62 +494,60 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.2.16" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "regex" -version = "1.7.1" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", + "regex-automata", "regex-syntax", ] [[package]] -name = "regex-syntax" -version = "0.6.28" +name = "regex-automata" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] [[package]] -name = "rustc-hash" -version = "1.1.0" +name = "regex-syntax" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] -name = "rustix" -version = "0.36.16" +name = "rustc-hash" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6da3636faa25820d8648e0e31c5d519bbb01f72fdf57131f0f5f7da5fed36eab" -dependencies = [ - "bitflags 1.3.2", - "errno", - "io-lifetimes", - "libc", - "linux-raw-sys 0.1.4", - "windows-sys 0.45.0", -] +checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497" [[package]] name = "rustix" -version = "0.37.3" +version = "0.37.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b24138615de35e32031d041a09032ef3487a616d901ca4db224e7d557efae2" +checksum = "fea8ca367a3a01fe35e6943c400addf443c0f57670e6ec51196f71a4b8762dd2" dependencies = [ "bitflags 1.3.2", "errno", "io-lifetimes", "libc", - "linux-raw-sys 0.3.8", - "windows-sys 0.45.0", + "linux-raw-sys", + "windows-sys 0.48.0", ] [[package]] @@ -574,9 +558,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "similar" -version = "2.2.1" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "420acb44afdae038210c99e69aae24109f32f15500aa708e81d46c9f29d55fcf" +checksum = "1de1d4f81173b03af4c0cbed3c898f6bff5b870e4a7f5d6f4057d62a7a4b686e" [[package]] name = "strsim" @@ -586,9 +570,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "syn" -version = "1.0.107" +version = "1.0.109" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2", "quote", @@ -597,9 +581,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.18" +version = "2.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e" +checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" dependencies = [ "proc-macro2", "quote", @@ -608,15 +592,16 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.4.0" +version = "3.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af18f7ae1acd354b992402e9ec5864359d693cd8a79dcbef59f76891701c1e95" +checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" dependencies = [ + "autocfg", "cfg-if", "fastrand", "redox_syscall", - "rustix 0.36.16", - "windows-sys 0.42.0", + "rustix", + "windows-sys 0.48.0", ] [[package]] @@ -639,15 +624,15 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.6" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" +checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" [[package]] name = "unicode-width" -version = "0.1.10" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "version_check" @@ -661,17 +646,6 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" -[[package]] -name = "which" -version = "4.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2441c784c52b289a054b7201fc93253e288f094e2f4be9058343127c4226a269" -dependencies = [ - "either", - "libc", - "once_cell", -] - [[package]] name = "winapi" version = "0.3.9" @@ -705,156 +679,139 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets 0.42.2", + "windows-targets 0.48.5", ] [[package]] name = "windows-sys" -version = "0.48.0" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.48.1", + "windows-targets 0.52.6", ] [[package]] name = "windows-targets" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" -version = "0.48.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.48.0", - "windows_aarch64_msvc 0.48.0", - "windows_i686_gnu 0.48.0", - "windows_i686_msvc 0.48.0", - "windows_x86_64_gnu 0.48.0", - "windows_x86_64_gnullvm 0.48.0", - "windows_x86_64_msvc 0.48.0", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] name = "windows_aarch64_gnullvm" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.48.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.48.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.48.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.48.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.48.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" - -[[package]] -name = "yansi-term" -version = "0.1.2" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5c30ade05e61656247b2e334a031dfd0cc466fadef865bdcdea8d537951bf1" -dependencies = [ - "winapi", -] +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" diff --git a/Cargo.toml b/Cargo.toml index 0730e061b4..b0a5bbb082 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,5 @@ [workspace] +resolver = "2" members = [ "bindgen", "bindgen-cli", @@ -7,27 +8,82 @@ members = [ "bindgen-tests/tests/quickchecking", "bindgen-tests/tests/expectations", ] - default-members = [ "bindgen", "bindgen-cli", "bindgen-tests", ] -# Config for 'cargo dist' -[workspace.metadata.dist] -# The preferred cargo-dist version to use in CI (Cargo.toml SemVer syntax) -cargo-dist-version = "0.3.1" -# CI backends to support -ci = ["github"] -# The installers to generate for each app -installers = ["shell", "powershell"] -# Target platforms to build apps for (Rust target-triple syntax) -targets = ["x86_64-unknown-linux-gnu", "aarch64-apple-darwin", "x86_64-apple-darwin"] -# Whether to consider the binaries in a package for distribution (defaults true) -dist = false -# Publish jobs to run in CI -pr-run-mode = "plan" +[workspace.package] +# If you change this, also update README.md +rust-version = "1.70.0" +edition = "2021" + +# All dependency version management is centralized here +[workspace.dependencies] +annotate-snippets = "0.11.4" +bindgen = { version = "0.71.1", path = "./bindgen", default-features = false } +bitflags = "2.2.1" +block = "0.1" +cc = "1.0" +cexpr = "0.6" +clang-sys = "1" +clap = "4" +clap_complete = "4" +env_logger = "0.10.0" +itertools = { version = ">=0.10,<0.14", default-features = false } +libloading = "0.8" +log = "0.4" +objc = "0.2" +owo-colors = "4.1.0" +prettyplease = "0.2.7" +proc-macro2 = "1.0.80" +quickcheck = "1.0" +quote = { version = "1", default-features = false } +regex = { version = "1.5.3", default-features = false } +rustc-hash = "2.1.0" +shlex = "1" +similar = "2.2.1" +syn = "2.0" +tempfile = "3" + +[workspace.lints.rust] +unused_qualifications = "warn" + +[workspace.lints.clippy] +pedantic = { level = "warn", priority = -1 } + +cast_possible_truncation = "allow" +cast_possible_wrap = "allow" +cast_precision_loss = "allow" +cast_sign_loss = "allow" +default_trait_access = "allow" +ignored_unit_patterns = "allow" +implicit_hasher = "allow" +items_after_statements = "allow" +match_same_arms = "allow" +maybe_infinite_iter = "allow" +missing_errors_doc = "allow" +missing_panics_doc = "allow" +module_name_repetitions = "allow" +must_use_candidate = "allow" +redundant_closure_for_method_calls = "allow" +return_self_not_must_use = "allow" +similar_names = "allow" +struct_excessive_bools = "allow" +struct_field_names = "allow" +unnecessary_wraps = "allow" +unreadable_literal = "allow" +used_underscore_binding = "allow" +wildcard_imports = "allow" + +# TODO +trivially_copy_pass_by_ref = "allow" +unused_self = "allow" + +# Theese seem to be ok to ignore for now +enum_glob_use = "allow" +too_many_lines = "allow" # Config for 'cargo release' [workspace.metadata.release] diff --git a/README.md b/README.md index 620ad0ab94..b35dee3bef 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,9 @@ extern "C" { ## MSRV -The `bindgen` minimum supported Rust version is **1.60.0**. +The `bindgen` minimum supported Rust version is **1.70.0**. -The `bindgen-cli` minimum supported Rust version is **1.64.0**. +The `bindgen-cli` minimum supported Rust version is **1.70.0**. No MSRV bump policy has been established yet, so MSRV may increase in any release. diff --git a/bindgen-cli/Cargo.toml b/bindgen-cli/Cargo.toml index e642790014..52fcaaeb1b 100644 --- a/bindgen-cli/Cargo.toml +++ b/bindgen-cli/Cargo.toml @@ -1,6 +1,8 @@ +lints.workspace = true + [package] authors = [ - "The rust-bindgen project contributors", + "The rust-bindgen project contributors", ] description = "Automatically generates Rust FFI bindings to C and C++ libraries." keywords = ["bindings", "ffi", "code-generation"] @@ -11,29 +13,27 @@ readme = "../README.md" repository = "https://github.com/rust-lang/rust-bindgen" documentation = "https://docs.rs/bindgen" homepage = "https://rust-lang.github.io/rust-bindgen/" -version = "0.69.4" -edition = "2018" -rust-version = "1.64.0" +version = "0.71.1" +rust-version.workspace = true +edition.workspace = true [[bin]] path = "main.rs" name = "bindgen" [dependencies] -bindgen = { path = "../bindgen", version = "=0.69.4", default-features = false, features = ["__cli", "experimental"] } -clap = { version = "4", features = ["derive"] } -clap_complete = "4" -env_logger = { version = "0.10.0", optional = true } -log = { version = "0.4", optional = true } -shlex = "1" +bindgen = { workspace = true, features = ["__cli", "experimental", "prettyplease"] } +env_logger = { workspace = true, optional = true } +log = { workspace = true, optional = true } +proc-macro2.workspace = true +shlex.workspace = true [features] -default = ["logging", "runtime", "which-rustfmt"] +default = ["logging", "runtime"] logging = ["bindgen/logging", "dep:env_logger", "dep:log"] static = ["bindgen/static"] runtime = ["bindgen/runtime"] -# Dynamically discover a `rustfmt` binary using the `which` crate -which-rustfmt = ["bindgen/which-rustfmt"] +prettyplease = ["bindgen/prettyplease"] ## The following features are for internal use and they shouldn't be used if ## you're not hacking on bindgen diff --git a/bindgen-cli/main.rs b/bindgen-cli/main.rs index 4b1bfad282..2d8d370ef1 100644 --- a/bindgen-cli/main.rs +++ b/bindgen-cli/main.rs @@ -1,14 +1,6 @@ -extern crate bindgen; -extern crate clap; -#[cfg(feature = "logging")] -extern crate env_logger; -#[cfg(feature = "logging")] -extern crate log; - use std::env; -mod options; -use crate::options::builder_from_flags; +use bindgen::builder_from_flags; #[cfg(feature = "logging")] fn clang_version_check() { @@ -43,34 +35,39 @@ pub fn main() { std::panic::set_hook(Box::new(move |info| { if verbose { - print_verbose_err() + print_verbose_err(); } - println!("{}", info); + eprintln!("{info}"); })); - let bindings = - builder.generate().expect("Unable to generate bindings"); + let bindings = match builder.generate() { + Ok(bindings) => bindings, + Err(err) => { + eprintln!("Unable to generate bindings: {err}"); + std::process::exit(1) + } + }; let _ = std::panic::take_hook(); bindings.write(output).expect("Unable to write output"); } Err(error) => { - println!("{}", error); + eprintln!("{error}"); std::process::exit(1); } }; } fn print_verbose_err() { - println!("Bindgen unexpectedly panicked"); - println!( + eprintln!("Bindgen unexpectedly panicked"); + eprintln!( "This may be caused by one of the known-unsupported \ things (https://rust-lang.github.io/rust-bindgen/cpp.html), \ please modify the bindgen flags to work around it as \ described in https://rust-lang.github.io/rust-bindgen/cpp.html" ); - println!( + eprintln!( "Otherwise, please file an issue at \ https://github.com/rust-lang/rust-bindgen/issues/new" ); diff --git a/bindgen-integration/Cargo.toml b/bindgen-integration/Cargo.toml index ccdd1467df..5c8c89d528 100644 --- a/bindgen-integration/Cargo.toml +++ b/bindgen-integration/Cargo.toml @@ -1,3 +1,5 @@ +lints.workspace = true + [package] name = "bindgen-integration" description = "A package to test various bindgen features" @@ -5,10 +7,12 @@ version = "0.1.0" authors = ["Emilio Cobos Álvarez "] publish = false build = "build.rs" +rust-version.workspace = true +edition.workspace = true [build-dependencies] -bindgen = { path = "../bindgen", features = ["experimental"] } -cc = "1.0" +bindgen = { workspace = true, default-features = true, features = ["experimental"] } +cc.workspace = true [features] static = ["bindgen/static"] diff --git a/bindgen-integration/build.rs b/bindgen-integration/build.rs index 7021f865d7..583f46ea93 100644 --- a/bindgen-integration/build.rs +++ b/bindgen-integration/build.rs @@ -1,10 +1,9 @@ extern crate bindgen; -extern crate cc; use bindgen::callbacks::{ DeriveInfo, IntKind, MacroParsingBehavior, ParseCallbacks, }; -use bindgen::{Builder, CargoCallbacks, EnumVariation, Formatter}; +use bindgen::{Builder, EnumVariation, Formatter}; use std::collections::HashSet; use std::env; use std::path::PathBuf; @@ -99,7 +98,7 @@ impl ParseCallbacks for MacroCallback { _ => { // The system might provide lots of functional macros. // Ensure we did not miss handling one that we meant to handle. - assert!(!name.starts_with("TESTMACRO_"), "name = {}", name); + assert!(!name.starts_with("TESTMACRO_"), "name = {name}"); } } } @@ -128,6 +127,20 @@ impl ParseCallbacks for MacroCallback { vec!["PartialEq".into()] } else if info.name == "MyOrderedEnum" { vec!["std::cmp::PartialOrd".into()] + } else if info.name == "TestDeriveOnAlias" { + vec!["std::cmp::PartialEq".into(), "std::cmp::PartialOrd".into()] + } else { + vec![] + } + } + + // Test the "custom attributes" capability. + fn add_attributes( + &self, + info: &bindgen::callbacks::AttributeInfo<'_>, + ) -> Vec { + if info.name == "Test" { + vec!["#[cfg_attr(test, derive(PartialOrd))]".into()] } else { vec![] } @@ -170,7 +183,7 @@ fn setup_macro_test() { let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); let out_rust_file = out_path.join("test.rs"); let out_rust_file_relative = out_rust_file - .strip_prefix(std::env::current_dir().unwrap().parent().unwrap()) + .strip_prefix(env::current_dir().unwrap().parent().unwrap()) .unwrap(); let out_dep_file = out_path.join("test.d"); @@ -193,6 +206,7 @@ fn setup_macro_test() { .blocklist_function("my_prefixed_function_to_remove") .constified_enum("my_prefixed_enum_to_be_constified") .opaque_type("my_prefixed_templated_foo") + .new_type_alias("TestDeriveOnAlias") .depfile(out_rust_file_relative.display().to_string(), &out_dep_file) .generate() .expect("Unable to generate bindings"); @@ -231,7 +245,9 @@ fn setup_wrap_static_fns_test() { // generate external bindings with the external .c and .h files let bindings = Builder::default() .header(input_header_file_path_str) - .parse_callbacks(Box::new(CargoCallbacks)) + .parse_callbacks(Box::new( + bindgen::CargoCallbacks::new().rerun_on_header_files(true), + )) .parse_callbacks(Box::new(WrappedVaListCallback)) .wrap_static_fns(true) .wrap_static_fns_path( @@ -242,7 +258,7 @@ fn setup_wrap_static_fns_test() { .expect("Unable to generate bindings"); println!("cargo:rustc-link-lib=static=wrap_static_fns"); // tell cargo to link libextern - println!("bindings generated: {}", bindings); + println!("bindings generated: {bindings}"); let obj_path = out_path.join("wrap_static_fns.o"); let lib_path = out_path.join("libwrap_static_fns.a"); diff --git a/bindgen-integration/cpp/Test.h b/bindgen-integration/cpp/Test.h index eee1974cbc..81a921b5f8 100644 --- a/bindgen-integration/cpp/Test.h +++ b/bindgen-integration/cpp/Test.h @@ -241,3 +241,6 @@ enum MyOrderedEnum { METER, LIGHTYEAR, }; + +// Used to test custom derives on new-type alias. See `test_custom_derive`. +typedef int TestDeriveOnAlias; diff --git a/bindgen-integration/src/lib.rs b/bindgen-integration/src/lib.rs index 04f6a5c9de..13f5bd889a 100755 --- a/bindgen-integration/src/lib.rs +++ b/bindgen-integration/src/lib.rs @@ -12,7 +12,6 @@ use std::ffi::CStr; use std::mem; use std::os::raw::c_int; -#[allow(unused)] use bindings::testing::Bar; // This type is generated from module_raw_line. type MacroInteger = isize; @@ -255,12 +254,12 @@ fn test_item_rename() { #[test] fn test_matching_with_rename() { assert_eq!(bindings::enum_to_be_constified_THREE, 3); - assert_eq!(unsafe { bindings::TEMPLATED_CONST_VALUE.len() }, 30); + assert_eq!(unsafe { bindings::TEMPLATED_CONST_VALUE.0.len() }, 30); } #[test] fn test_macro_customintkind_path() { - let v: &std::any::Any = &bindings::TESTMACRO_CUSTOMINTKIND_PATH; + let v: &dyn std::any::Any = &bindings::TESTMACRO_CUSTOMINTKIND_PATH; assert!(v.is::()) } @@ -289,6 +288,22 @@ fn test_custom_derive() { assert!(meter < lightyear); assert!(meter > micron); + + // The `add_derives` callback should have added `#[derive(PartialEq, PartialOrd)]` + // to the `TestDeriveOnAlias` new-type alias. If it didn't, this will fail to compile. + let test1 = unsafe { bindings::TestDeriveOnAlias(5) }; + let test2 = unsafe { bindings::TestDeriveOnAlias(6) }; + assert!(test1 < test2); + assert!(!(test1 > test2)); +} + +#[test] +fn test_custom_attributes() { + // The `add_attributes` callback should have added `#[cfg_attr(test, derive(PartialOrd))])` + // to the `Test` struct. If it didn't, this will fail to compile. + let test1 = unsafe { bindings::Test::new(5) }; + let test2 = unsafe { bindings::Test::new(6) }; + assert!(test1 < test2); } #[test] diff --git a/bindgen-tests/Cargo.toml b/bindgen-tests/Cargo.toml index 1c06c3f10d..77a28ca3cb 100644 --- a/bindgen-tests/Cargo.toml +++ b/bindgen-tests/Cargo.toml @@ -1,25 +1,27 @@ +lints.workspace = true + [package] name = "bindgen-tests" -edition = "2018" version = "0.1.0" publish = false +rust-version.workspace = true +edition.workspace = true [dev-dependencies] -bindgen = { path = "../bindgen", features = ["__cli", "experimental"] } -clap = { version = "4", features = ["derive"] } -clap_complete = "4" -shlex = "1" -prettyplease = { version = "0.2.7", features = ["verbatim"] } -syn = { version = "2.0" } -tempfile = "3" -similar = { version = "2.2.1", features = ["inline"] } -owo-colors = "3.5.0" +bindgen = { workspace = true, default-features = true, features = ["__cli", "experimental"] } +owo-colors.workspace = true +prettyplease = { workspace = true, features = ["verbatim"] } +proc-macro2.workspace = true +regex.workspace = true +shlex.workspace = true +similar = { workspace = true, features = ["inline"] } +syn.workspace = true +tempfile.workspace = true [features] logging = ["bindgen/logging"] static = ["bindgen/static"] runtime = ["bindgen/runtime"] -which-rustfmt = ["bindgen/which-rustfmt"] __testing_only_extra_assertions = ["bindgen/__testing_only_extra_assertions"] __testing_only_libclang_9 = ["bindgen/__testing_only_libclang_9"] diff --git a/bindgen-tests/build.rs b/bindgen-tests/build.rs index 6b2f2c7274..8fb33716a1 100644 --- a/bindgen-tests/build.rs +++ b/bindgen-tests/build.rs @@ -1,6 +1,5 @@ use std::char; use std::env; -use std::ffi::OsStr; use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; @@ -12,10 +11,9 @@ pub fn main() { let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let headers_dir = manifest_dir.join("tests").join("headers"); - let headers = match fs::read_dir(headers_dir) { - Ok(dir) => dir, + let Ok(headers) = fs::read_dir(headers_dir) else { // We may not have headers directory after packaging. - Err(..) => return, + return; }; let entries = @@ -24,24 +22,19 @@ pub fn main() { println!("cargo:rerun-if-changed=tests/headers"); for entry in entries { - match entry.path().extension().and_then(OsStr::to_str) { - Some("h") | Some("hpp") => { - let func = entry - .file_name() - .to_str() - .unwrap() - .replace(|c| !char::is_alphanumeric(c), "_") - .replace("__", "_") - .to_lowercase(); - writeln!( - dst, - "test_header!(header_{}, {:?});", - func, - entry.path(), - ) + // TODO: file_is_cpp() in bindgen/lib.rs checks for hpp,hxx,hh, and h++ - should this be consistent? + if entry.path().extension().is_some_and(|ext| { + ext.eq_ignore_ascii_case("h") || ext.eq_ignore_ascii_case("hpp") + }) { + let func = entry + .file_name() + .to_str() + .unwrap() + .replace(|c| !char::is_alphanumeric(c), "_") + .replace("__", "_") + .to_lowercase(); + writeln!(dst, "test_header!(header_{func}, {:?});", entry.path()) .unwrap(); - } - _ => {} } } diff --git a/bindgen-tests/tests/expectations/Cargo.toml b/bindgen-tests/tests/expectations/Cargo.toml index adb95d56d2..975fd16678 100644 --- a/bindgen-tests/tests/expectations/Cargo.toml +++ b/bindgen-tests/tests/expectations/Cargo.toml @@ -7,10 +7,40 @@ authors = [ "Emilio Cobos Álvarez ", "The Servo project developers", ] -edition = "2018" publish = false +rust-version.workspace = true +edition.workspace = true [dependencies] -block = "0.1" -libloading = "0.7" -objc = "0.2" +block.workspace = true +libloading.workspace = true +objc.workspace = true + +# Both of these sections need to be copied here from the workspace because +# Cargo currently does not allow overriding workspace settings in a member +[lints.rust] +### FIXME: these might need to be fixed, +### esp the calling convention, because it is a hard error now +# deprecated = "allow" +# invalid-value = "allow" +# unsupported_calling_conventions = "allow" +# +# Different from the workspace +dead_code = "allow" +non-snake-case = "allow" +non_camel_case_types = "allow" +non_upper_case_globals = "allow" +unexpected-cfgs = "allow" +unused_qualifications = "allow" + +[lints.clippy] +disallowed-names = "allow" +manual-c-str-literals = "allow" +missing-safety-doc = "allow" +op-ref = "allow" +ptr-offset-with-cast = "allow" +semicolon_if_nothing_returned = "allow" +too-many-arguments = "allow" +transmute-int-to-bool = "allow" +unnecessary-cast = "allow" +useless-transmute = "allow" diff --git a/bindgen-tests/tests/expectations/lib.rs b/bindgen-tests/tests/expectations/lib.rs index 562dc5548d..e69de29bb2 100755 --- a/bindgen-tests/tests/expectations/lib.rs +++ b/bindgen-tests/tests/expectations/lib.rs @@ -1,3 +0,0 @@ -#![allow(dead_code)] -#![allow(non_camel_case_types)] -#![allow(non_upper_case_globals)] diff --git a/bindgen-tests/tests/expectations/tests/16-byte-alignment.rs b/bindgen-tests/tests/expectations/tests/16-byte-alignment.rs index b93cae0465..c55d0b075b 100644 --- a/bindgen-tests/tests/expectations/tests/16-byte-alignment.rs +++ b/bindgen-tests/tests/expectations/tests/16-byte-alignment.rs @@ -18,66 +18,35 @@ pub struct rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1 { pub dport: u16, pub sport: u16, } -#[test] -fn bindgen_test_layout_rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dport) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(dport), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sport) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(sport), - ), - ); -} -#[test] -fn bindgen_test_layout_rte_ipv4_tuple__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ipv4_tuple__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ipv4_tuple__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sctp_tag) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple__bindgen_ty_1), - "::", - stringify!(sctp_tag), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1::dport", + ][::std::mem::offset_of!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1, dport) + - 0usize]; + [ + "Offset of field: rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1::sport", + ][::std::mem::offset_of!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1, sport) + - 2usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_ipv4_tuple__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of rte_ipv4_tuple__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_ipv4_tuple__bindgen_ty_1::sctp_tag", + ][::std::mem::offset_of!(rte_ipv4_tuple__bindgen_ty_1, sctp_tag) - 0usize]; +}; impl Default for rte_ipv4_tuple__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -87,41 +56,17 @@ impl Default for rte_ipv4_tuple__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_rte_ipv4_tuple() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rte_ipv4_tuple)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ipv4_tuple)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).src_addr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple), - "::", - stringify!(src_addr), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dst_addr) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple), - "::", - stringify!(dst_addr), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_ipv4_tuple"][::std::mem::size_of::() - 12usize]; + ["Alignment of rte_ipv4_tuple"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_ipv4_tuple::src_addr", + ][::std::mem::offset_of!(rte_ipv4_tuple, src_addr) - 0usize]; + [ + "Offset of field: rte_ipv4_tuple::dst_addr", + ][::std::mem::offset_of!(rte_ipv4_tuple, dst_addr) - 4usize]; +}; impl Default for rte_ipv4_tuple { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -150,66 +95,35 @@ pub struct rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1 { pub dport: u16, pub sport: u16, } -#[test] -fn bindgen_test_layout_rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dport) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(dport), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sport) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(sport), - ), - ); -} -#[test] -fn bindgen_test_layout_rte_ipv6_tuple__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ipv6_tuple__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ipv6_tuple__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sctp_tag) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple__bindgen_ty_1), - "::", - stringify!(sctp_tag), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1::dport", + ][::std::mem::offset_of!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1, dport) + - 0usize]; + [ + "Offset of field: rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1::sport", + ][::std::mem::offset_of!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1, sport) + - 2usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_ipv6_tuple__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of rte_ipv6_tuple__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_ipv6_tuple__bindgen_ty_1::sctp_tag", + ][::std::mem::offset_of!(rte_ipv6_tuple__bindgen_ty_1, sctp_tag) - 0usize]; +}; impl Default for rte_ipv6_tuple__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -219,41 +133,17 @@ impl Default for rte_ipv6_tuple__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_rte_ipv6_tuple() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 36usize, - concat!("Size of: ", stringify!(rte_ipv6_tuple)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ipv6_tuple)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).src_addr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple), - "::", - stringify!(src_addr), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dst_addr) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple), - "::", - stringify!(dst_addr), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_ipv6_tuple"][::std::mem::size_of::() - 36usize]; + ["Alignment of rte_ipv6_tuple"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_ipv6_tuple::src_addr", + ][::std::mem::offset_of!(rte_ipv6_tuple, src_addr) - 0usize]; + [ + "Offset of field: rte_ipv6_tuple::dst_addr", + ][::std::mem::offset_of!(rte_ipv6_tuple, dst_addr) - 16usize]; +}; impl Default for rte_ipv6_tuple { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -270,31 +160,19 @@ pub union rte_thash_tuple { pub v4: rte_ipv4_tuple, pub v6: rte_ipv6_tuple, } -#[test] -fn bindgen_test_layout_rte_thash_tuple() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 48usize, - concat!("Size of: ", stringify!(rte_thash_tuple)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(rte_thash_tuple)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).v4) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_thash_tuple), "::", stringify!(v4)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).v6) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_thash_tuple), "::", stringify!(v6)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_thash_tuple"][::std::mem::size_of::() - 48usize]; + [ + "Alignment of rte_thash_tuple", + ][::std::mem::align_of::() - 16usize]; + [ + "Offset of field: rte_thash_tuple::v4", + ][::std::mem::offset_of!(rte_thash_tuple, v4) - 0usize]; + [ + "Offset of field: rte_thash_tuple::v6", + ][::std::mem::offset_of!(rte_thash_tuple, v6) - 0usize]; +}; impl Default for rte_thash_tuple { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/16-byte-alignment_1_0.rs b/bindgen-tests/tests/expectations/tests/16-byte-alignment_1_0.rs deleted file mode 100644 index a7d7518a34..0000000000 --- a/bindgen-tests/tests/expectations/tests/16-byte-alignment_1_0.rs +++ /dev/null @@ -1,349 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_ipv4_tuple { - pub src_addr: u32, - pub dst_addr: u32, - pub __bindgen_anon_1: rte_ipv4_tuple__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_ipv4_tuple__bindgen_ty_1 { - pub __bindgen_anon_1: __BindgenUnionField< - rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1, - >, - pub sctp_tag: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1 { - pub dport: u16, - pub sport: u16, -} -#[test] -fn bindgen_test_layout_rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dport) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(dport), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sport) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(sport), - ), - ); -} -impl Clone for rte_ipv4_tuple__bindgen_ty_1__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_ipv4_tuple__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ipv4_tuple__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ipv4_tuple__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sctp_tag) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple__bindgen_ty_1), - "::", - stringify!(sctp_tag), - ), - ); -} -impl Clone for rte_ipv4_tuple__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_ipv4_tuple() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rte_ipv4_tuple)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ipv4_tuple)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).src_addr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple), - "::", - stringify!(src_addr), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dst_addr) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv4_tuple), - "::", - stringify!(dst_addr), - ), - ); -} -impl Clone for rte_ipv4_tuple { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_ipv6_tuple { - pub src_addr: [u8; 16usize], - pub dst_addr: [u8; 16usize], - pub __bindgen_anon_1: rte_ipv6_tuple__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_ipv6_tuple__bindgen_ty_1 { - pub __bindgen_anon_1: __BindgenUnionField< - rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1, - >, - pub sctp_tag: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1 { - pub dport: u16, - pub sport: u16, -} -#[test] -fn bindgen_test_layout_rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dport) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(dport), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sport) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(sport), - ), - ); -} -impl Clone for rte_ipv6_tuple__bindgen_ty_1__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_ipv6_tuple__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ipv6_tuple__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ipv6_tuple__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sctp_tag) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple__bindgen_ty_1), - "::", - stringify!(sctp_tag), - ), - ); -} -impl Clone for rte_ipv6_tuple__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_ipv6_tuple() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 36usize, - concat!("Size of: ", stringify!(rte_ipv6_tuple)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ipv6_tuple)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).src_addr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple), - "::", - stringify!(src_addr), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dst_addr) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(rte_ipv6_tuple), - "::", - stringify!(dst_addr), - ), - ); -} -impl Clone for rte_ipv6_tuple { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Copy)] -pub struct rte_thash_tuple { - pub v4: __BindgenUnionField, - pub v6: __BindgenUnionField, - pub bindgen_union_field: [u8; 48usize], -} -#[test] -fn bindgen_test_layout_rte_thash_tuple() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 48usize, - concat!("Size of: ", stringify!(rte_thash_tuple)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).v4) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_thash_tuple), "::", stringify!(v4)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).v6) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_thash_tuple), "::", stringify!(v6)), - ); -} -impl Clone for rte_thash_tuple { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_thash_tuple { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} diff --git a/bindgen-tests/tests/expectations/tests/abi-override.rs b/bindgen-tests/tests/expectations/tests/abi-override.rs index 13132f9c45..369bfd8d32 100644 --- a/bindgen-tests/tests/expectations/tests/abi-override.rs +++ b/bindgen-tests/tests/expectations/tests/abi-override.rs @@ -1,14 +1,15 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "fastcall" { +#![cfg(target = "i686-pc-windows-msvc")] +unsafe extern "fastcall" { pub fn foo(); } -extern "stdcall" { +unsafe extern "stdcall" { pub fn bar(); } -extern "C" { +unsafe extern "C" { pub fn baz(); } -extern "system" { +unsafe extern "system" { pub fn qux(); } pub type boo = ::std::option::Option; diff --git a/bindgen-tests/tests/expectations/tests/abi_variadic_function.rs b/bindgen-tests/tests/expectations/tests/abi_variadic_function.rs index 3cb7248c93..b57ddafd32 100644 --- a/bindgen-tests/tests/expectations/tests/abi_variadic_function.rs +++ b/bindgen-tests/tests/expectations/tests/abi_variadic_function.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z1bcz"] pub fn b(arg1: ::std::os::raw::c_char, ...) -> ::std::os::raw::c_char; } diff --git a/bindgen-tests/tests/expectations/tests/accessors.rs b/bindgen-tests/tests/expectations/tests/accessors.rs index 9aa33d65b5..586edf2d79 100644 --- a/bindgen-tests/tests/expectations/tests/accessors.rs +++ b/bindgen-tests/tests/expectations/tests/accessors.rs @@ -10,63 +10,23 @@ pub struct SomeAccessors { ///
pub mImmutableAccessor: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_SomeAccessors() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(SomeAccessors)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(SomeAccessors)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mNoAccessor) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(SomeAccessors), - "::", - stringify!(mNoAccessor), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBothAccessors) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(SomeAccessors), - "::", - stringify!(mBothAccessors), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mUnsafeAccessors) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(SomeAccessors), - "::", - stringify!(mUnsafeAccessors), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mImmutableAccessor) as usize - ptr as usize - }, - 12usize, - concat!( - "Offset of field: ", - stringify!(SomeAccessors), - "::", - stringify!(mImmutableAccessor), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of SomeAccessors"][::std::mem::size_of::() - 16usize]; + ["Alignment of SomeAccessors"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: SomeAccessors::mNoAccessor", + ][::std::mem::offset_of!(SomeAccessors, mNoAccessor) - 0usize]; + [ + "Offset of field: SomeAccessors::mBothAccessors", + ][::std::mem::offset_of!(SomeAccessors, mBothAccessors) - 4usize]; + [ + "Offset of field: SomeAccessors::mUnsafeAccessors", + ][::std::mem::offset_of!(SomeAccessors, mUnsafeAccessors) - 8usize]; + [ + "Offset of field: SomeAccessors::mImmutableAccessor", + ][::std::mem::offset_of!(SomeAccessors, mImmutableAccessor) - 12usize]; +}; impl SomeAccessors { #[inline] pub fn get_mBothAccessors(&self) -> &::std::os::raw::c_int { @@ -96,43 +56,17 @@ pub struct AllAccessors { pub mBothAccessors: ::std::os::raw::c_int, pub mAlsoBothAccessors: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_AllAccessors() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(AllAccessors)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(AllAccessors)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBothAccessors) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(AllAccessors), - "::", - stringify!(mBothAccessors), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mAlsoBothAccessors) as usize - ptr as usize - }, - 4usize, - concat!( - "Offset of field: ", - stringify!(AllAccessors), - "::", - stringify!(mAlsoBothAccessors), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AllAccessors"][::std::mem::size_of::() - 8usize]; + ["Alignment of AllAccessors"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: AllAccessors::mBothAccessors", + ][::std::mem::offset_of!(AllAccessors, mBothAccessors) - 0usize]; + [ + "Offset of field: AllAccessors::mAlsoBothAccessors", + ][::std::mem::offset_of!(AllAccessors, mAlsoBothAccessors) - 4usize]; +}; impl AllAccessors { #[inline] pub fn get_mBothAccessors(&self) -> &::std::os::raw::c_int { @@ -158,43 +92,19 @@ pub struct AllUnsafeAccessors { pub mBothAccessors: ::std::os::raw::c_int, pub mAlsoBothAccessors: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_AllUnsafeAccessors() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(AllUnsafeAccessors)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(AllUnsafeAccessors)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBothAccessors) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(AllUnsafeAccessors), - "::", - stringify!(mBothAccessors), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mAlsoBothAccessors) as usize - ptr as usize - }, - 4usize, - concat!( - "Offset of field: ", - stringify!(AllUnsafeAccessors), - "::", - stringify!(mAlsoBothAccessors), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AllUnsafeAccessors"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of AllUnsafeAccessors", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: AllUnsafeAccessors::mBothAccessors", + ][::std::mem::offset_of!(AllUnsafeAccessors, mBothAccessors) - 0usize]; + [ + "Offset of field: AllUnsafeAccessors::mAlsoBothAccessors", + ][::std::mem::offset_of!(AllUnsafeAccessors, mAlsoBothAccessors) - 4usize]; +}; impl AllUnsafeAccessors { #[inline] pub unsafe fn get_mBothAccessors(&self) -> &::std::os::raw::c_int { @@ -225,63 +135,27 @@ pub struct ContradictAccessors { ///
pub mImmutableAccessor: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_ContradictAccessors() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(ContradictAccessors)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ContradictAccessors)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBothAccessors) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContradictAccessors), - "::", - stringify!(mBothAccessors), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mNoAccessors) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(ContradictAccessors), - "::", - stringify!(mNoAccessors), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mUnsafeAccessors) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(ContradictAccessors), - "::", - stringify!(mUnsafeAccessors), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mImmutableAccessor) as usize - ptr as usize - }, - 12usize, - concat!( - "Offset of field: ", - stringify!(ContradictAccessors), - "::", - stringify!(mImmutableAccessor), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ContradictAccessors", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of ContradictAccessors", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: ContradictAccessors::mBothAccessors", + ][::std::mem::offset_of!(ContradictAccessors, mBothAccessors) - 0usize]; + [ + "Offset of field: ContradictAccessors::mNoAccessors", + ][::std::mem::offset_of!(ContradictAccessors, mNoAccessors) - 4usize]; + [ + "Offset of field: ContradictAccessors::mUnsafeAccessors", + ][::std::mem::offset_of!(ContradictAccessors, mUnsafeAccessors) - 8usize]; + [ + "Offset of field: ContradictAccessors::mImmutableAccessor", + ][::std::mem::offset_of!(ContradictAccessors, mImmutableAccessor) - 12usize]; +}; impl ContradictAccessors { #[inline] pub fn get_mBothAccessors(&self) -> &::std::os::raw::c_int { @@ -310,26 +184,14 @@ impl ContradictAccessors { pub struct Replaced { pub mAccessor: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Replaced() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Replaced)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Replaced)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mAccessor) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Replaced), "::", stringify!(mAccessor)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Replaced"][::std::mem::size_of::() - 4usize]; + ["Alignment of Replaced"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: Replaced::mAccessor", + ][::std::mem::offset_of!(Replaced, mAccessor) - 0usize]; +}; impl Replaced { #[inline] pub fn get_mAccessor(&self) -> &::std::os::raw::c_int { @@ -346,26 +208,14 @@ impl Replaced { pub struct Wrapper { pub mReplaced: Replaced, } -#[test] -fn bindgen_test_layout_Wrapper() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Wrapper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Wrapper)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mReplaced) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Wrapper), "::", stringify!(mReplaced)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Wrapper"][::std::mem::size_of::() - 4usize]; + ["Alignment of Wrapper"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: Wrapper::mReplaced", + ][::std::mem::offset_of!(Wrapper, mReplaced) - 0usize]; +}; impl Wrapper { #[inline] pub fn get_mReplaced(&self) -> &Replaced { diff --git a/bindgen-tests/tests/expectations/tests/allowlist-file.rs b/bindgen-tests/tests/expectations/tests/allowlist-file.rs index ce591f59d3..b1fb170de0 100644 --- a/bindgen-tests/tests/expectations/tests/allowlist-file.rs +++ b/bindgen-tests/tests/expectations/tests/allowlist-file.rs @@ -1,10 +1,10 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] pub const SOME_DEFUN: u32 = 123; -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z12SomeFunctionv"] pub fn SomeFunction(); } -extern "C" { +unsafe extern "C" { pub static mut someVar: ::std::os::raw::c_int; } #[repr(C)] @@ -12,20 +12,12 @@ extern "C" { pub struct someClass { pub _address: u8, } -#[test] -fn bindgen_test_layout_someClass() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(someClass)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(someClass)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of someClass"][::std::mem::size_of::() - 1usize]; + ["Alignment of someClass"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN9someClass16somePublicMethodEi"] pub fn someClass_somePublicMethod(this: *mut someClass, foo: ::std::os::raw::c_int); } @@ -35,10 +27,10 @@ impl someClass { someClass_somePublicMethod(self, foo) } } -extern "C" { +unsafe extern "C" { pub fn ExternFunction(); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3foo18NamespacedFunctionEv"] pub fn foo_NamespacedFunction(); } @@ -47,31 +39,18 @@ extern "C" { pub struct StructWithAllowlistedDefinition { pub other: *mut StructWithAllowlistedFwdDecl, } -#[test] -fn bindgen_test_layout_StructWithAllowlistedDefinition() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(StructWithAllowlistedDefinition)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(StructWithAllowlistedDefinition)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).other) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(StructWithAllowlistedDefinition), - "::", - stringify!(other), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of StructWithAllowlistedDefinition", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of StructWithAllowlistedDefinition", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: StructWithAllowlistedDefinition::other", + ][::std::mem::offset_of!(StructWithAllowlistedDefinition, other) - 0usize]; +}; impl Default for StructWithAllowlistedDefinition { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -86,53 +65,28 @@ impl Default for StructWithAllowlistedDefinition { pub struct StructWithAllowlistedFwdDecl { pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_StructWithAllowlistedFwdDecl() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(StructWithAllowlistedFwdDecl)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(StructWithAllowlistedFwdDecl)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(StructWithAllowlistedFwdDecl), - "::", - stringify!(b), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of StructWithAllowlistedFwdDecl", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of StructWithAllowlistedFwdDecl", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: StructWithAllowlistedFwdDecl::b", + ][::std::mem::offset_of!(StructWithAllowlistedFwdDecl, b) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AllowlistMe { pub foo: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_AllowlistMe() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(AllowlistMe)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(AllowlistMe)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AllowlistMe), "::", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AllowlistMe"][::std::mem::size_of::() - 4usize]; + ["Alignment of AllowlistMe"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: AllowlistMe::foo", + ][::std::mem::offset_of!(AllowlistMe, foo) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/allowlist-namespaces-basic.rs b/bindgen-tests/tests/expectations/tests/allowlist-namespaces-basic.rs index 726a596953..151d03f4a4 100644 --- a/bindgen-tests/tests/expectations/tests/allowlist-namespaces-basic.rs +++ b/bindgen-tests/tests/expectations/tests/allowlist-namespaces-basic.rs @@ -14,19 +14,11 @@ pub mod root { pub struct Helper { pub _address: u8, } - #[test] - fn bindgen_test_layout_Helper() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Helper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Helper)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Helper"][::std::mem::size_of::() - 1usize]; + ["Alignment of Helper"][::std::mem::align_of::() - 1usize]; + }; } } } diff --git a/bindgen-tests/tests/expectations/tests/allowlist-namespaces.rs b/bindgen-tests/tests/expectations/tests/allowlist-namespaces.rs index 1445bf73a2..563c97ca1d 100644 --- a/bindgen-tests/tests/expectations/tests/allowlist-namespaces.rs +++ b/bindgen-tests/tests/expectations/tests/allowlist-namespaces.rs @@ -14,44 +14,24 @@ pub mod root { pub struct Helper { pub _address: u8, } - #[test] - fn bindgen_test_layout_Helper() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Helper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Helper)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Helper"][::std::mem::size_of::() - 1usize]; + ["Alignment of Helper"][::std::mem::align_of::() - 1usize]; + }; } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Test { pub helper: root::outer::inner::Helper, } - #[test] - fn bindgen_test_layout_Test() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Test)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).helper) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(helper)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Test"][::std::mem::size_of::() - 1usize]; + ["Alignment of Test"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: Test::helper", + ][::std::mem::offset_of!(Test, helper) - 0usize]; + }; } } diff --git a/bindgen-tests/tests/expectations/tests/allowlist_basic.rs b/bindgen-tests/tests/expectations/tests/allowlist_basic.rs index 902c6ba503..a1c6919739 100644 --- a/bindgen-tests/tests/expectations/tests/allowlist_basic.rs +++ b/bindgen-tests/tests/expectations/tests/allowlist_basic.rs @@ -2,15 +2,15 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct AllowlistMe { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub foo: ::std::os::raw::c_int, pub bar: AllowlistMe_Inner, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct AllowlistMe_Inner { - pub bar: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub bar: T, } impl Default for AllowlistMe_Inner { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/allowlist_fix.rs b/bindgen-tests/tests/expectations/tests/allowlist_fix.rs index e3ce7bc100..772772c56c 100644 --- a/bindgen-tests/tests/expectations/tests/allowlist_fix.rs +++ b/bindgen-tests/tests/expectations/tests/allowlist_fix.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] pub enum Test {} -extern "C" { +unsafe extern "C" { pub fn Servo_Test(a: *mut Test); } diff --git a/bindgen-tests/tests/expectations/tests/allowlist_item.rs b/bindgen-tests/tests/expectations/tests/allowlist_item.rs index eaca8aec22..93eab7e147 100644 --- a/bindgen-tests/tests/expectations/tests/allowlist_item.rs +++ b/bindgen-tests/tests/expectations/tests/allowlist_item.rs @@ -5,26 +5,12 @@ pub const FooDefault: u32 = 0; pub struct Foo { pub field: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).field) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(field)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo::field"][::std::mem::offset_of!(Foo, field) - 0usize]; +}; +unsafe extern "C" { pub fn FooNew(value: ::std::os::raw::c_int) -> Foo; } diff --git a/bindgen-tests/tests/expectations/tests/allowlisted-item-references-no-hash.rs b/bindgen-tests/tests/expectations/tests/allowlisted-item-references-no-hash.rs index b9a3fb5c16..6c1d13a837 100644 --- a/bindgen-tests/tests/expectations/tests/allowlisted-item-references-no-hash.rs +++ b/bindgen-tests/tests/expectations/tests/allowlisted-item-references-no-hash.rs @@ -4,41 +4,19 @@ pub struct NoHash { pub _address: u8, } -#[test] -fn bindgen_test_layout_NoHash() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(NoHash)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(NoHash)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoHash"][::std::mem::size_of::() - 1usize]; + ["Alignment of NoHash"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AllowlistMe { pub a: NoHash, } -#[test] -fn bindgen_test_layout_AllowlistMe() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(AllowlistMe)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(AllowlistMe)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AllowlistMe), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AllowlistMe"][::std::mem::size_of::() - 1usize]; + ["Alignment of AllowlistMe"][::std::mem::align_of::() - 1usize]; + ["Offset of field: AllowlistMe::a"][::std::mem::offset_of!(AllowlistMe, a) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/allowlisted-item-references-no-partialeq.rs b/bindgen-tests/tests/expectations/tests/allowlisted-item-references-no-partialeq.rs index 1e763880e1..b969727dbb 100644 --- a/bindgen-tests/tests/expectations/tests/allowlisted-item-references-no-partialeq.rs +++ b/bindgen-tests/tests/expectations/tests/allowlisted-item-references-no-partialeq.rs @@ -4,41 +4,19 @@ pub struct NoPartialEq { pub _address: u8, } -#[test] -fn bindgen_test_layout_NoPartialEq() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(NoPartialEq)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(NoPartialEq)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoPartialEq"][::std::mem::size_of::() - 1usize]; + ["Alignment of NoPartialEq"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AllowlistMe { pub a: NoPartialEq, } -#[test] -fn bindgen_test_layout_AllowlistMe() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(AllowlistMe)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(AllowlistMe)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AllowlistMe), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AllowlistMe"][::std::mem::size_of::() - 1usize]; + ["Alignment of AllowlistMe"][::std::mem::align_of::() - 1usize]; + ["Offset of field: AllowlistMe::a"][::std::mem::offset_of!(AllowlistMe, a) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/allowlisted_item_references_no_copy.rs b/bindgen-tests/tests/expectations/tests/allowlisted_item_references_no_copy.rs index 0058371966..8c671b4e84 100644 --- a/bindgen-tests/tests/expectations/tests/allowlisted_item_references_no_copy.rs +++ b/bindgen-tests/tests/expectations/tests/allowlisted_item_references_no_copy.rs @@ -4,41 +4,19 @@ pub struct NoCopy { pub _address: u8, } -#[test] -fn bindgen_test_layout_NoCopy() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(NoCopy)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(NoCopy)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoCopy"][::std::mem::size_of::() - 1usize]; + ["Alignment of NoCopy"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default)] pub struct AllowlistMe { pub a: NoCopy, } -#[test] -fn bindgen_test_layout_AllowlistMe() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(AllowlistMe)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(AllowlistMe)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AllowlistMe), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AllowlistMe"][::std::mem::size_of::() - 1usize]; + ["Alignment of AllowlistMe"][::std::mem::align_of::() - 1usize]; + ["Offset of field: AllowlistMe::a"][::std::mem::offset_of!(AllowlistMe, a) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/annotation_hide.rs b/bindgen-tests/tests/expectations/tests/annotation_hide.rs index 1ec81ba6e2..e79c88214d 100644 --- a/bindgen-tests/tests/expectations/tests/annotation_hide.rs +++ b/bindgen-tests/tests/expectations/tests/annotation_hide.rs @@ -6,37 +6,21 @@ pub struct D { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_D() { - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(D))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(D)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of D"][::std::mem::size_of::() - 4usize]; + ["Alignment of D"][::std::mem::align_of::() - 4usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct NotAnnotated { pub f: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_NotAnnotated() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NotAnnotated)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NotAnnotated)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(NotAnnotated), "::", stringify!(f)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NotAnnotated"][::std::mem::size_of::() - 4usize]; + ["Alignment of NotAnnotated"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: NotAnnotated::f", + ][::std::mem::offset_of!(NotAnnotated, f) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/anon-fields-prefix.rs b/bindgen-tests/tests/expectations/tests/anon-fields-prefix.rs index 813bde9e55..2b96804c9b 100644 --- a/bindgen-tests/tests/expectations/tests/anon-fields-prefix.rs +++ b/bindgen-tests/tests/expectations/tests/anon-fields-prefix.rs @@ -13,51 +13,24 @@ pub struct color__bindgen_ty_1 { pub g: ::std::os::raw::c_uchar, pub b: ::std::os::raw::c_uchar, } -#[test] -fn bindgen_test_layout_color__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 3usize, - concat!("Size of: ", stringify!(color__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(color__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).r) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(color__bindgen_ty_1), - "::", - stringify!(r), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).g) as usize - ptr as usize }, - 1usize, - concat!( - "Offset of field: ", - stringify!(color__bindgen_ty_1), - "::", - stringify!(g), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(color__bindgen_ty_1), - "::", - stringify!(b), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of color__bindgen_ty_1", + ][::std::mem::size_of::() - 3usize]; + [ + "Alignment of color__bindgen_ty_1", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: color__bindgen_ty_1::r", + ][::std::mem::offset_of!(color__bindgen_ty_1, r) - 0usize]; + [ + "Offset of field: color__bindgen_ty_1::g", + ][::std::mem::offset_of!(color__bindgen_ty_1, g) - 1usize]; + [ + "Offset of field: color__bindgen_ty_1::b", + ][::std::mem::offset_of!(color__bindgen_ty_1, b) - 2usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct color__bindgen_ty_2 { @@ -65,71 +38,30 @@ pub struct color__bindgen_ty_2 { pub u: ::std::os::raw::c_uchar, pub v: ::std::os::raw::c_uchar, } -#[test] -fn bindgen_test_layout_color__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 3usize, - concat!("Size of: ", stringify!(color__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(color__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(color__bindgen_ty_2), - "::", - stringify!(y), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 1usize, - concat!( - "Offset of field: ", - stringify!(color__bindgen_ty_2), - "::", - stringify!(u), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).v) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(color__bindgen_ty_2), - "::", - stringify!(v), - ), - ); -} -#[test] -fn bindgen_test_layout_color() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 3usize, - concat!("Size of: ", stringify!(color)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(color)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).v3) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(color), "::", stringify!(v3)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of color__bindgen_ty_2", + ][::std::mem::size_of::() - 3usize]; + [ + "Alignment of color__bindgen_ty_2", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: color__bindgen_ty_2::y", + ][::std::mem::offset_of!(color__bindgen_ty_2, y) - 0usize]; + [ + "Offset of field: color__bindgen_ty_2::u", + ][::std::mem::offset_of!(color__bindgen_ty_2, u) - 1usize]; + [ + "Offset of field: color__bindgen_ty_2::v", + ][::std::mem::offset_of!(color__bindgen_ty_2, v) - 2usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of color"][::std::mem::size_of::() - 3usize]; + ["Alignment of color"][::std::mem::align_of::() - 1usize]; + ["Offset of field: color::v3"][::std::mem::offset_of!(color, v3) - 0usize]; +}; impl Default for color { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/anon_enum.rs b/bindgen-tests/tests/expectations/tests/anon_enum.rs index a3ad1db9f0..c3790a2a24 100644 --- a/bindgen-tests/tests/expectations/tests/anon_enum.rs +++ b/bindgen-tests/tests/expectations/tests/anon_enum.rs @@ -11,31 +11,13 @@ pub const Test_T_NONE: Test__bindgen_ty_1 = Test__bindgen_ty_1::T_NONE; pub enum Test__bindgen_ty_1 { T_NONE = 0, } -#[test] -fn bindgen_test_layout_Test() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Test)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 8usize]; + ["Alignment of Test"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Test::foo"][::std::mem::offset_of!(Test, foo) - 0usize]; + ["Offset of field: Test::bar"][::std::mem::offset_of!(Test, bar) - 4usize]; +}; #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum Baz { diff --git a/bindgen-tests/tests/expectations/tests/anon_enum_allowlist_item.rs b/bindgen-tests/tests/expectations/tests/anon_enum_allowlist_item.rs new file mode 100644 index 0000000000..4d28c3abc7 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/anon_enum_allowlist_item.rs @@ -0,0 +1,4 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub const NODE_FLAG_FOO: _bindgen_ty_1 = 0; +pub const NODE_FLAG_BAR: _bindgen_ty_1 = 1; +pub type _bindgen_ty_1 = ::std::os::raw::c_uint; diff --git a/bindgen-tests/tests/expectations/tests/anon_enum_blocklist.rs b/bindgen-tests/tests/expectations/tests/anon_enum_blocklist.rs new file mode 100644 index 0000000000..28ab3ad786 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/anon_enum_blocklist.rs @@ -0,0 +1,4 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub const FLAG_Z: _bindgen_ty_2 = 0; +pub const FLAG_W: _bindgen_ty_2 = 1; +pub type _bindgen_ty_2 = ::std::os::raw::c_uint; diff --git a/bindgen-tests/tests/expectations/tests/anon_enum_trait.rs b/bindgen-tests/tests/expectations/tests/anon_enum_trait.rs index 37fe6d810c..cfd4d03200 100644 --- a/bindgen-tests/tests/expectations/tests/anon_enum_trait.rs +++ b/bindgen-tests/tests/expectations/tests/anon_enum_trait.rs @@ -30,16 +30,8 @@ pub const Foo_Baz: Foo__bindgen_ty_1 = Foo__bindgen_ty_1::Bar; pub enum Foo__bindgen_ty_1 { Bar = 0, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/anon_struct_in_union.rs b/bindgen-tests/tests/expectations/tests/anon_struct_in_union.rs index a012f1692e..dceca1adf3 100644 --- a/bindgen-tests/tests/expectations/tests/anon_struct_in_union.rs +++ b/bindgen-tests/tests/expectations/tests/anon_struct_in_union.rs @@ -14,56 +14,26 @@ pub union s__bindgen_ty_1 { pub struct s__bindgen_ty_1_inner { pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_s__bindgen_ty_1_inner() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(s__bindgen_ty_1_inner)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(s__bindgen_ty_1_inner)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(s__bindgen_ty_1_inner), - "::", - stringify!(b), - ), - ); -} -#[test] -fn bindgen_test_layout_s__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(s__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(s__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).field) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(s__bindgen_ty_1), - "::", - stringify!(field), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of s__bindgen_ty_1_inner", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of s__bindgen_ty_1_inner", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: s__bindgen_ty_1_inner::b", + ][::std::mem::offset_of!(s__bindgen_ty_1_inner, b) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of s__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + ["Alignment of s__bindgen_ty_1"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: s__bindgen_ty_1::field", + ][::std::mem::offset_of!(s__bindgen_ty_1, field) - 0usize]; +}; impl Default for s__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -73,22 +43,12 @@ impl Default for s__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_s() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(s))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(s)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(s), "::", stringify!(u)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of s"][::std::mem::size_of::() - 4usize]; + ["Alignment of s"][::std::mem::align_of::() - 4usize]; + ["Offset of field: s::u"][::std::mem::offset_of!(s, u) - 0usize]; +}; impl Default for s { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/anon_struct_in_union_1_0.rs b/bindgen-tests/tests/expectations/tests/anon_struct_in_union_1_0.rs deleted file mode 100644 index c3b11f63e8..0000000000 --- a/bindgen-tests/tests/expectations/tests/anon_struct_in_union_1_0.rs +++ /dev/null @@ -1,141 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct s { - pub u: s__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct s__bindgen_ty_1 { - pub field: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct s__bindgen_ty_1_inner { - pub b: ::std::os::raw::c_int, -} -#[test] -fn bindgen_test_layout_s__bindgen_ty_1_inner() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(s__bindgen_ty_1_inner)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(s__bindgen_ty_1_inner)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(s__bindgen_ty_1_inner), - "::", - stringify!(b), - ), - ); -} -impl Clone for s__bindgen_ty_1_inner { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_s__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(s__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(s__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).field) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(s__bindgen_ty_1), - "::", - stringify!(field), - ), - ); -} -impl Clone for s__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_s() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(s))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(s)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(s), "::", stringify!(u)), - ); -} -impl Clone for s { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/anon_union.rs b/bindgen-tests/tests/expectations/tests/anon_union.rs index d77658df83..d9bf3cf183 100644 --- a/bindgen-tests/tests/expectations/tests/anon_union.rs +++ b/bindgen-tests/tests/expectations/tests/anon_union.rs @@ -51,19 +51,11 @@ impl Default for TErrorResult { pub struct ErrorResult { pub _base: TErrorResult, } -#[test] -fn bindgen_test_layout_ErrorResult() { - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(ErrorResult)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ErrorResult)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ErrorResult"][::std::mem::size_of::() - 24usize]; + ["Alignment of ErrorResult"][::std::mem::align_of::() - 8usize]; +}; impl Default for ErrorResult { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -73,16 +65,12 @@ impl Default for ErrorResult { } } } -#[test] -fn __bindgen_test_layout_TErrorResult_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of template specialization: ", stringify!(TErrorResult)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of template specialization: ", stringify!(TErrorResult)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: TErrorResult_open0_int_close0", + ][::std::mem::size_of::() - 24usize]; + [ + "Align of template specialization: TErrorResult_open0_int_close0", + ][::std::mem::align_of::() - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/anon_union_1_0.rs b/bindgen-tests/tests/expectations/tests/anon_union_1_0.rs deleted file mode 100644 index c7e24da1c7..0000000000 --- a/bindgen-tests/tests/expectations/tests/anon_union_1_0.rs +++ /dev/null @@ -1,129 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub struct TErrorResult { - pub mResult: ::std::os::raw::c_int, - pub __bindgen_anon_1: TErrorResult__bindgen_ty_1, - pub mMightHaveUnreported: bool, - pub mUnionState: TErrorResult_UnionState, -} -pub const TErrorResult_UnionState_HasException: TErrorResult_UnionState = TErrorResult_UnionState::HasMessage; -#[repr(i32)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum TErrorResult_UnionState { - HasMessage = 0, -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct TErrorResult_Message { - _unused: [u8; 0], -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct TErrorResult_DOMExceptionInfo { - _unused: [u8; 0], -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct TErrorResult__bindgen_ty_1 { - pub mMessage: __BindgenUnionField<*mut TErrorResult_Message>, - pub mDOMExceptionInfo: __BindgenUnionField<*mut TErrorResult_DOMExceptionInfo>, - pub bindgen_union_field: u64, -} -impl Default for TErrorResult { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct ErrorResult { - pub _base: TErrorResult, -} -#[test] -fn bindgen_test_layout_ErrorResult() { - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(ErrorResult)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ErrorResult)), - ); -} -impl Clone for ErrorResult { - fn clone(&self) -> Self { - *self - } -} -impl Default for ErrorResult { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[test] -fn __bindgen_test_layout_TErrorResult_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of template specialization: ", stringify!(TErrorResult)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of template specialization: ", stringify!(TErrorResult)), - ); -} diff --git a/bindgen-tests/tests/expectations/tests/anonymous-template-types.rs b/bindgen-tests/tests/expectations/tests/anonymous-template-types.rs index 9009b0d7c2..f6c894d8b5 100644 --- a/bindgen-tests/tests/expectations/tests/anonymous-template-types.rs +++ b/bindgen-tests/tests/expectations/tests/anonymous-template-types.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Foo { - pub t_member: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t_member: T, } impl Default for Foo { fn default() -> Self { @@ -22,8 +22,8 @@ pub struct Bar { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Quux { - pub v_member: V, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub v_member: V, } impl Default for Quux { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/arg_keyword.rs b/bindgen-tests/tests/expectations/tests/arg_keyword.rs index e7dd10b048..5a48aba011 100644 --- a/bindgen-tests/tests/expectations/tests/arg_keyword.rs +++ b/bindgen-tests/tests/expectations/tests/arg_keyword.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z3fooPKc"] pub fn foo(type_: *const ::std::os::raw::c_char); } diff --git a/bindgen-tests/tests/expectations/tests/array-of-zero-sized-types.rs b/bindgen-tests/tests/expectations/tests/array-of-zero-sized-types.rs index 9eb483cc6a..4630abd275 100644 --- a/bindgen-tests/tests/expectations/tests/array-of-zero-sized-types.rs +++ b/bindgen-tests/tests/expectations/tests/array-of-zero-sized-types.rs @@ -5,19 +5,11 @@ pub struct Empty { pub _address: u8, } -#[test] -fn bindgen_test_layout_Empty() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Empty)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Empty)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Empty"][::std::mem::size_of::() - 1usize]; + ["Alignment of Empty"][::std::mem::align_of::() - 1usize]; +}; /** This should not get an `_address` byte, since each `Empty` gets one, meaning that this object is addressable.*/ #[repr(C)] @@ -25,28 +17,11 @@ fn bindgen_test_layout_Empty() { pub struct HasArrayOfEmpty { pub empties: [Empty; 10usize], } -#[test] -fn bindgen_test_layout_HasArrayOfEmpty() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 10usize, - concat!("Size of: ", stringify!(HasArrayOfEmpty)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(HasArrayOfEmpty)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).empties) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(HasArrayOfEmpty), - "::", - stringify!(empties), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of HasArrayOfEmpty"][::std::mem::size_of::() - 10usize]; + ["Alignment of HasArrayOfEmpty"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: HasArrayOfEmpty::empties", + ][::std::mem::offset_of!(HasArrayOfEmpty, empties) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/atomic-constant.rs b/bindgen-tests/tests/expectations/tests/atomic-constant.rs new file mode 100644 index 0000000000..344e632085 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/atomic-constant.rs @@ -0,0 +1,7 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +unsafe extern "C" { + pub static mut a: ::std::os::raw::c_int; +} +unsafe extern "C" { + pub static mut b: ::std::os::raw::c_int; +} diff --git a/bindgen-tests/tests/expectations/tests/attribute-custom-cli.rs b/bindgen-tests/tests/expectations/tests/attribute-custom-cli.rs new file mode 100644 index 0000000000..55353116d3 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/attribute-custom-cli.rs @@ -0,0 +1,48 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +#[doc(hidden)] +#[derive(Default)] +pub struct foo_struct { + pub inner: ::std::os::raw::c_int, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo_struct"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo_struct"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo_struct::inner", + ][::std::mem::offset_of!(foo_struct, inner) - 0usize]; +}; +#[repr(u32)] +#[cfg_attr(test, derive(PartialOrd, Copy))] +#[derive(Clone, Hash, PartialEq, Eq)] +pub enum foo_enum { + inner = 0, +} +#[repr(C)] +#[doc(hidden)] +#[derive(Clone)] +#[derive(Copy)] +pub union foo_union { + pub fst: ::std::mem::ManuallyDrop<::std::os::raw::c_int>, + pub snd: ::std::mem::ManuallyDrop, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo_union"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo_union"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo_union::fst"][::std::mem::offset_of!(foo_union, fst) - 0usize]; + ["Offset of field: foo_union::snd"][::std::mem::offset_of!(foo_union, snd) - 0usize]; +}; +#[repr(C)] +pub struct non_matching { + pub inner: ::std::os::raw::c_int, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of non_matching"][::std::mem::size_of::() - 4usize]; + ["Alignment of non_matching"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: non_matching::inner", + ][::std::mem::offset_of!(non_matching, inner) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/attribute-custom.rs b/bindgen-tests/tests/expectations/tests/attribute-custom.rs new file mode 100644 index 0000000000..6d616d3f3e --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/attribute-custom.rs @@ -0,0 +1,22 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +///
+#[repr(C)] +#[derive(Debug)] +pub struct my_type { + pub a: ::std::os::raw::c_int, +} +/**
+
*/ +#[repr(C)] +#[derive(Debug)] +#[derive(Clone)] +pub struct my_type2 { + pub a: ::std::os::raw::c_uint, +} +///
+#[repr(C)] +#[derive(Debug)] +#[derive(Clone)] +pub struct my_type3 { + pub a: ::std::os::raw::c_ulong, +} diff --git a/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result.rs b/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result.rs index b3ded6636e..07eb7a80f6 100644 --- a/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result.rs +++ b/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result.rs @@ -6,16 +6,8 @@ pub struct Foo { } #[test] fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); + assert_eq!(::std::mem::size_of::(), 1usize, "Size of Foo"); + assert_eq!(::std::mem::align_of::(), 1usize, "Alignment of Foo"); } extern "C" { #[must_use] diff --git a/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result_no_attribute_detection.rs b/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result_no_attribute_detection.rs index 15cfef051f..aa01540b0e 100644 --- a/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result_no_attribute_detection.rs +++ b/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result_no_attribute_detection.rs @@ -6,16 +6,8 @@ pub struct Foo { } #[test] fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); + assert_eq!(::std::mem::size_of::(), 1usize, "Size of Foo"); + assert_eq!(::std::mem::align_of::(), 1usize, "Alignment of Foo"); } extern "C" { #[link_name = "\u{1}_ZN3Foo3fooEi"] diff --git a/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result_pre_1_27.rs b/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result_pre_1_27.rs deleted file mode 100644 index 15cfef051f..0000000000 --- a/bindgen-tests/tests/expectations/tests/attribute_warn_unused_result_pre_1_27.rs +++ /dev/null @@ -1,33 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Debug, Default, Copy, Clone)] -pub struct Foo { - pub _address: u8, -} -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "C" { - #[link_name = "\u{1}_ZN3Foo3fooEi"] - pub fn Foo_foo(this: *mut Foo, arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; -} -impl Foo { - #[inline] - pub unsafe fn foo(&mut self, arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int { - Foo_foo(self, arg1) - } -} -extern "C" { - #[link_name = "\u{1}_Z3fooi"] - pub fn foo(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; -} diff --git a/bindgen-tests/tests/expectations/tests/auto.rs b/bindgen-tests/tests/expectations/tests/auto.rs index 340bc670dc..ba93e7a20b 100644 --- a/bindgen-tests/tests/expectations/tests/auto.rs +++ b/bindgen-tests/tests/expectations/tests/auto.rs @@ -5,25 +5,17 @@ pub struct Foo { pub _address: u8, } pub const Foo_kFoo: bool = true; -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Bar { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z5Test2v"] pub fn Test2() -> ::std::os::raw::c_uint; } diff --git a/bindgen-tests/tests/expectations/tests/base-to-derived.rs b/bindgen-tests/tests/expectations/tests/base-to-derived.rs index 1d6643219c..22ef4fdb08 100644 --- a/bindgen-tests/tests/expectations/tests/base-to-derived.rs +++ b/bindgen-tests/tests/expectations/tests/base-to-derived.rs @@ -4,16 +4,8 @@ pub struct false_type { pub _address: u8, } -#[test] -fn bindgen_test_layout_false_type() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(false_type)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(false_type)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of false_type"][::std::mem::size_of::() - 1usize]; + ["Alignment of false_type"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/bindgen-union-inside-namespace.rs b/bindgen-tests/tests/expectations/tests/bindgen-union-inside-namespace.rs index 2a73a439d1..f3d7893b00 100644 --- a/bindgen-tests/tests/expectations/tests/bindgen-union-inside-namespace.rs +++ b/bindgen-tests/tests/expectations/tests/bindgen-union-inside-namespace.rs @@ -1,89 +1,41 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] pub mod root { - #[repr(C)] - pub struct __BindgenUnionField(::std::marker::PhantomData); - impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } - } - impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } - } - impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } - } - impl ::std::marker::Copy for __BindgenUnionField {} - impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } - } - impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} - } - impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } - } - impl ::std::cmp::Eq for __BindgenUnionField {} #[allow(unused_imports)] use self::super::root; pub mod foo { #[allow(unused_imports)] use self::super::super::root; #[repr(C)] - #[derive(Debug, Default, Copy)] - pub struct Bar { - pub foo: root::__BindgenUnionField<::std::os::raw::c_int>, - pub bar: root::__BindgenUnionField<::std::os::raw::c_int>, - pub bindgen_union_field: u32, + #[derive(Copy, Clone)] + pub union Bar { + pub foo: ::std::os::raw::c_int, + pub bar: ::std::os::raw::c_int, } #[test] fn bindgen_test_layout_Bar() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); + assert_eq!(::std::mem::size_of::(), 4usize, "Size of Bar"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of Bar"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(foo)), + "Offset of field: Bar::foo", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(bar)), + "Offset of field: Bar::bar", ); } - impl Clone for Bar { - fn clone(&self) -> Self { - *self + impl Default for Bar { + fn default() -> Self { + unsafe { + let mut s: Self = ::std::mem::uninitialized(); + ::std::ptr::write_bytes(&mut s, 0, 1); + s + } } } } diff --git a/bindgen-tests/tests/expectations/tests/bitfield-32bit-overflow.rs b/bindgen-tests/tests/expectations/tests/bitfield-32bit-overflow.rs index ea126bbbc1..81ce12a5c9 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield-32bit-overflow.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield-32bit-overflow.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -89,19 +151,11 @@ pub struct MuchBitfield { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 5usize]>, } -#[test] -fn bindgen_test_layout_MuchBitfield() { - assert_eq!( - ::std::mem::size_of::(), - 5usize, - concat!("Size of: ", stringify!(MuchBitfield)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(MuchBitfield)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of MuchBitfield"][::std::mem::size_of::() - 5usize]; + ["Alignment of MuchBitfield"][::std::mem::align_of::() - 1usize]; +}; impl MuchBitfield { #[inline] pub fn m0(&self) -> ::std::os::raw::c_char { @@ -115,6 +169,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m0_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m0_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m1(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u8) } } @@ -126,6 +204,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m1_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m1_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m2(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u8) } } @@ -137,6 +239,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m2_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m2_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m3(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u8) } } @@ -148,6 +274,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m3_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 3usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m3_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m4(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u8) } } @@ -159,6 +309,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m4_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 4usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m4_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m5(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u8) } } @@ -170,6 +344,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m5_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 5usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m5_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m6(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u8) } } @@ -181,6 +379,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m6_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 6usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m6_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m7(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u8) } } @@ -192,6 +414,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m7_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 7usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m7_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m8(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u8) } } @@ -203,6 +449,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m8_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 8usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m8_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m9(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u8) } } @@ -214,6 +484,30 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m9_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 9usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_m9_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m10(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u8) } } @@ -225,6 +519,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m10_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 10usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m10_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m11(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u8) } } @@ -236,6 +555,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m11_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 11usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m11_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m12(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u8) } } @@ -247,6 +591,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m12_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 12usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m12_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m13(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u8) } } @@ -258,6 +627,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m13_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 13usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m13_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m14(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 1u8) as u8) } } @@ -269,6 +663,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m14_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 14usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m14_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m15(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 1u8) as u8) } } @@ -280,6 +699,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m15_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 15usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m15_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m16(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 1u8) as u8) } } @@ -291,6 +735,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m16_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m16_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m17(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(17usize, 1u8) as u8) } } @@ -302,6 +771,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m17_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 17usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m17_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 17usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m18(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 1u8) as u8) } } @@ -313,6 +807,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m18_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 18usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m18_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m19(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(19usize, 1u8) as u8) } } @@ -324,6 +843,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m19_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 19usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m19_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 19usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m20(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 1u8) as u8) } } @@ -335,6 +879,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m20_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 20usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m20_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m21(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(21usize, 1u8) as u8) } } @@ -346,6 +915,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m21_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 21usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m21_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 21usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m22(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(22usize, 1u8) as u8) } } @@ -357,6 +951,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m22_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 22usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m22_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 22usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m23(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(23usize, 1u8) as u8) } } @@ -368,6 +987,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m23_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 23usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m23_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 23usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m24(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 1u8) as u8) } } @@ -379,6 +1023,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m24_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 24usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m24_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m25(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(25usize, 1u8) as u8) } } @@ -390,6 +1059,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m25_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 25usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m25_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 25usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m26(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(26usize, 1u8) as u8) } } @@ -401,6 +1095,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m26_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 26usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m26_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 26usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m27(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(27usize, 1u8) as u8) } } @@ -412,6 +1131,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m27_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 27usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m27_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 27usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m28(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(28usize, 1u8) as u8) } } @@ -423,6 +1167,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m28_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 28usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m28_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 28usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m29(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(29usize, 1u8) as u8) } } @@ -434,6 +1203,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m29_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 29usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m29_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 29usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m30(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(30usize, 1u8) as u8) } } @@ -445,6 +1239,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m30_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 30usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m30_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 30usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m31(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(31usize, 1u8) as u8) } } @@ -456,6 +1275,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m31_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 31usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m31_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 31usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn m32(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 1u8) as u8) } } @@ -467,6 +1311,31 @@ impl MuchBitfield { } } #[inline] + pub unsafe fn m32_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 32usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_m32_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 5usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( m0: ::std::os::raw::c_char, m1: ::std::os::raw::c_char, diff --git a/bindgen-tests/tests/expectations/tests/bitfield-enum-basic.rs b/bindgen-tests/tests/expectations/tests/bitfield-enum-basic.rs index ab6a923201..aecb9dc639 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield-enum-basic.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield-enum-basic.rs @@ -1,14 +1,8 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] impl Foo { pub const Bar: Foo = Foo(2); -} -impl Foo { pub const Baz: Foo = Foo(4); -} -impl Foo { pub const Duplicated: Foo = Foo(4); -} -impl Foo { pub const Negative: Foo = Foo(-3); } impl ::std::ops::BitOr for Foo { @@ -42,14 +36,8 @@ impl ::std::ops::BitAndAssign for Foo { pub struct Foo(pub ::std::os::raw::c_int); impl Buz { pub const Bar: Buz = Buz(2); -} -impl Buz { pub const Baz: Buz = Buz(4); -} -impl Buz { pub const Duplicated: Buz = Buz(4); -} -impl Buz { pub const Negative: Buz = Buz(-3); } impl ::std::ops::BitOr for Buz { @@ -148,16 +136,8 @@ impl ::std::ops::BitAndAssign for Dummy__bindgen_ty_1 { #[repr(transparent)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Dummy__bindgen_ty_1(pub ::std::os::raw::c_uint); -#[test] -fn bindgen_test_layout_Dummy() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Dummy)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Dummy)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Dummy"][::std::mem::size_of::() - 1usize]; + ["Alignment of Dummy"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/bitfield-enum-repr-c.rs b/bindgen-tests/tests/expectations/tests/bitfield-enum-repr-c.rs index 0403e844e2..df5a69eddd 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield-enum-repr-c.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield-enum-repr-c.rs @@ -1,14 +1,8 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] impl Foo { pub const Bar: Foo = Foo(2); -} -impl Foo { pub const Baz: Foo = Foo(4); -} -impl Foo { pub const Duplicated: Foo = Foo(4); -} -impl Foo { pub const Negative: Foo = Foo(-3); } impl ::std::ops::BitOr for Foo { @@ -37,6 +31,6 @@ impl ::std::ops::BitAndAssign for Foo { self.0 &= rhs.0; } } -#[repr(C)] +#[repr(transparent)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Foo(pub ::std::os::raw::c_int); diff --git a/bindgen-tests/tests/expectations/tests/bitfield-enum-repr-transparent.rs b/bindgen-tests/tests/expectations/tests/bitfield-enum-repr-transparent.rs index 0b5202dfe3..df5a69eddd 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield-enum-repr-transparent.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield-enum-repr-transparent.rs @@ -1,14 +1,8 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] impl Foo { pub const Bar: Foo = Foo(2); -} -impl Foo { pub const Baz: Foo = Foo(4); -} -impl Foo { pub const Duplicated: Foo = Foo(4); -} -impl Foo { pub const Negative: Foo = Foo(-3); } impl ::std::ops::BitOr for Foo { diff --git a/bindgen-tests/tests/expectations/tests/bitfield-large.rs b/bindgen-tests/tests/expectations/tests/bitfield-large.rs index f5b337cf45..8024d88c3b 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield-large.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield-large.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[repr(align(16))] @@ -90,19 +152,11 @@ pub struct HasBigBitfield { pub _bitfield_align_1: [u64; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, } -#[test] -fn bindgen_test_layout_HasBigBitfield() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(HasBigBitfield)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(HasBigBitfield)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of HasBigBitfield"][::std::mem::size_of::() - 16usize]; + ["Alignment of HasBigBitfield"][::std::mem::align_of::() - 16usize]; +}; impl HasBigBitfield { #[inline] pub fn x(&self) -> i128 { @@ -116,6 +170,31 @@ impl HasBigBitfield { } } #[inline] + pub unsafe fn x_raw(this: *const Self) -> i128 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 128u8) + as u128, + ) + } + } + #[inline] + pub unsafe fn set_x_raw(this: *mut Self, val: i128) { + unsafe { + let val: u128 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 128u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1(x: i128) -> __BindgenBitfieldUnit<[u8; 16usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 16usize]> = Default::default(); __bindgen_bitfield_unit @@ -137,19 +216,15 @@ pub struct HasTwoBigBitfields { pub _bitfield_align_1: [u64; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, } -#[test] -fn bindgen_test_layout_HasTwoBigBitfields() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(HasTwoBigBitfields)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(HasTwoBigBitfields)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of HasTwoBigBitfields", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of HasTwoBigBitfields", + ][::std::mem::align_of::() - 16usize]; +}; impl HasTwoBigBitfields { #[inline] pub fn x(&self) -> i128 { @@ -163,6 +238,31 @@ impl HasTwoBigBitfields { } } #[inline] + pub unsafe fn x_raw(this: *const Self) -> i128 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 80u8) + as u128, + ) + } + } + #[inline] + pub unsafe fn set_x_raw(this: *mut Self, val: i128) { + unsafe { + let val: u128 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 80u8, + val as u64, + ) + } + } + #[inline] pub fn y(&self) -> i128 { unsafe { ::std::mem::transmute(self._bitfield_1.get(80usize, 48u8) as u128) } } @@ -174,6 +274,31 @@ impl HasTwoBigBitfields { } } #[inline] + pub unsafe fn y_raw(this: *const Self) -> i128 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 80usize, 48u8) + as u128, + ) + } + } + #[inline] + pub unsafe fn set_y_raw(this: *mut Self, val: i128) { + unsafe { + let val: u128 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 80usize, + 48u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1(x: i128, y: i128) -> __BindgenBitfieldUnit<[u8; 16usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 16usize]> = Default::default(); __bindgen_bitfield_unit diff --git a/bindgen-tests/tests/expectations/tests/bitfield-linux-32.rs b/bindgen-tests/tests/expectations/tests/bitfield-linux-32.rs index 4500be292f..8b0b37b481 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield-linux-32.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield-linux-32.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C, packed(4))] #[derive(Debug, Default, Copy, Clone)] @@ -90,26 +152,12 @@ pub struct Test { pub _bitfield_align_1: [u64; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } -#[test] -fn bindgen_test_layout_Test() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Test)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 16usize]; + ["Alignment of Test"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Test::foo"][::std::mem::offset_of!(Test, foo) - 0usize]; +}; impl Test { #[inline] pub fn x(&self) -> u64 { @@ -123,6 +171,31 @@ impl Test { } } #[inline] + pub unsafe fn x_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 56u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_x_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 56u8, + val as u64, + ) + } + } + #[inline] pub fn y(&self) -> u64 { unsafe { ::std::mem::transmute(self._bitfield_1.get(56usize, 8u8) as u64) } } @@ -134,6 +207,31 @@ impl Test { } } #[inline] + pub unsafe fn y_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 56usize, 8u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_y_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 56usize, + 8u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1(x: u64, y: u64) -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit diff --git a/bindgen-tests/tests/expectations/tests/bitfield-method-same-name.rs b/bindgen-tests/tests/expectations/tests/bitfield-method-same-name.rs index ce3ea41e75..84e152f3fd 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield-method-same-name.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield-method-same-name.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -89,28 +151,20 @@ pub struct Foo { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo4typeEv"] pub fn Foo_type(this: *mut Foo) -> ::std::os::raw::c_char; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo9set_type_Ec"] pub fn Foo_set_type_(this: *mut Foo, c: ::std::os::raw::c_char); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo8set_typeEc"] pub fn Foo_set_type(this: *mut Foo, c: ::std::os::raw::c_char); } @@ -127,6 +181,35 @@ impl Foo { } } #[inline] + pub unsafe fn type__bindgen_bitfield_raw( + this: *const Self, + ) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 3u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_type__bindgen_bitfield_raw( + this: *mut Self, + val: ::std::os::raw::c_char, + ) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 3u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( type__bindgen_bitfield: ::std::os::raw::c_char, ) -> __BindgenBitfieldUnit<[u8; 1usize]> { diff --git a/bindgen-tests/tests/expectations/tests/bitfield_align.rs b/bindgen-tests/tests/expectations/tests/bitfield_align.rs index 8002327981..5f1321bbb1 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield_align.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield_align.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[repr(align(4))] @@ -92,27 +154,13 @@ pub struct A { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, pub y: ::std::os::raw::c_uchar, } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 3usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(y)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 4usize]; + ["Alignment of A"][::std::mem::align_of::() - 4usize]; + ["Offset of field: A::x"][::std::mem::offset_of!(A, x) - 0usize]; + ["Offset of field: A::y"][::std::mem::offset_of!(A, y) - 3usize]; +}; impl A { #[inline] pub fn b1(&self) -> ::std::os::raw::c_uint { @@ -126,6 +174,31 @@ impl A { } } #[inline] + pub unsafe fn b1_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b1_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b2(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } } @@ -137,6 +210,31 @@ impl A { } } #[inline] + pub unsafe fn b2_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b2_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b3(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } } @@ -148,6 +246,31 @@ impl A { } } #[inline] + pub unsafe fn b3_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b3_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b4(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } } @@ -159,6 +282,31 @@ impl A { } } #[inline] + pub unsafe fn b4_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 3usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b4_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b5(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } } @@ -170,6 +318,31 @@ impl A { } } #[inline] + pub unsafe fn b5_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 4usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b5_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b6(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } } @@ -181,6 +354,31 @@ impl A { } } #[inline] + pub unsafe fn b6_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 5usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b6_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b7(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } } @@ -192,6 +390,31 @@ impl A { } } #[inline] + pub unsafe fn b7_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 6usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b7_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b8(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } } @@ -203,6 +426,31 @@ impl A { } } #[inline] + pub unsafe fn b8_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 7usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b8_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b9(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } } @@ -214,6 +462,31 @@ impl A { } } #[inline] + pub unsafe fn b9_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 8usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b9_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b10(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } } @@ -225,6 +498,31 @@ impl A { } } #[inline] + pub unsafe fn b10_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 9usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b10_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( b1: ::std::os::raw::c_uint, b2: ::std::os::raw::c_uint, @@ -337,15 +635,11 @@ pub struct B { pub _bitfield_align_1: [u32; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, } -#[test] -fn bindgen_test_layout_B() { - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(B)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of B"][::std::mem::size_of::() - 4usize]; + ["Alignment of B"][::std::mem::align_of::() - 4usize]; +}; impl B { #[inline] pub fn foo(&self) -> ::std::os::raw::c_uint { @@ -359,6 +653,31 @@ impl B { } } #[inline] + pub unsafe fn foo_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 31u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_foo_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 31u8, + val as u64, + ) + } + } + #[inline] pub fn bar(&self) -> ::std::os::raw::c_uchar { unsafe { ::std::mem::transmute(self._bitfield_1.get(31usize, 1u8) as u8) } } @@ -370,6 +689,31 @@ impl B { } } #[inline] + pub unsafe fn bar_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 31usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_bar_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 31usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( foo: ::std::os::raw::c_uint, bar: ::std::os::raw::c_uchar, @@ -404,27 +748,13 @@ pub struct C { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub baz: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 8usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 8usize]; + ["Alignment of C"][::std::mem::align_of::() - 4usize]; + ["Offset of field: C::x"][::std::mem::offset_of!(C, x) - 0usize]; + ["Offset of field: C::baz"][::std::mem::offset_of!(C, baz) - 4usize]; +}; impl C { #[inline] pub fn b1(&self) -> ::std::os::raw::c_uint { @@ -438,6 +768,31 @@ impl C { } } #[inline] + pub unsafe fn b1_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b1_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b2(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } } @@ -449,6 +804,31 @@ impl C { } } #[inline] + pub unsafe fn b2_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b2_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( b1: ::std::os::raw::c_uint, b2: ::std::os::raw::c_uint, @@ -483,19 +863,11 @@ pub struct Date1 { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, pub __bindgen_padding_0: u8, } -#[test] -fn bindgen_test_layout_Date1() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Date1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(Date1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Date1"][::std::mem::size_of::() - 4usize]; + ["Alignment of Date1"][::std::mem::align_of::() - 2usize]; +}; impl Date1 { #[inline] pub fn nWeekDay(&self) -> ::std::os::raw::c_ushort { @@ -509,6 +881,31 @@ impl Date1 { } } #[inline] + pub unsafe fn nWeekDay_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 3u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nWeekDay_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 3u8, + val as u64, + ) + } + } + #[inline] pub fn nMonthDay(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 6u8) as u16) } } @@ -520,6 +917,31 @@ impl Date1 { } } #[inline] + pub unsafe fn nMonthDay_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 3usize, 6u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nMonthDay_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 6u8, + val as u64, + ) + } + } + #[inline] pub fn nMonth(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 5u8) as u16) } } @@ -531,6 +953,31 @@ impl Date1 { } } #[inline] + pub unsafe fn nMonth_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 9usize, 5u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nMonth_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 5u8, + val as u64, + ) + } + } + #[inline] pub fn nYear(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 8u8) as u16) } } @@ -542,6 +989,31 @@ impl Date1 { } } #[inline] + pub unsafe fn nYear_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 8u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nYear_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 8u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( nWeekDay: ::std::os::raw::c_ushort, nMonthDay: ::std::os::raw::c_ushort, @@ -595,19 +1067,11 @@ pub struct Date2 { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, } -#[test] -fn bindgen_test_layout_Date2() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Date2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(Date2)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Date2"][::std::mem::size_of::() - 4usize]; + ["Alignment of Date2"][::std::mem::align_of::() - 2usize]; +}; impl Date2 { #[inline] pub fn nWeekDay(&self) -> ::std::os::raw::c_ushort { @@ -621,6 +1085,31 @@ impl Date2 { } } #[inline] + pub unsafe fn nWeekDay_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 3u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nWeekDay_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 3u8, + val as u64, + ) + } + } + #[inline] pub fn nMonthDay(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 6u8) as u16) } } @@ -632,6 +1121,31 @@ impl Date2 { } } #[inline] + pub unsafe fn nMonthDay_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 3usize, 6u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nMonthDay_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 6u8, + val as u64, + ) + } + } + #[inline] pub fn nMonth(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 5u8) as u16) } } @@ -643,6 +1157,31 @@ impl Date2 { } } #[inline] + pub unsafe fn nMonth_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 9usize, 5u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nMonth_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 5u8, + val as u64, + ) + } + } + #[inline] pub fn nYear(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 8u8) as u16) } } @@ -654,6 +1193,31 @@ impl Date2 { } } #[inline] + pub unsafe fn nYear_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 8u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nYear_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 8u8, + val as u64, + ) + } + } + #[inline] pub fn byte(&self) -> ::std::os::raw::c_uchar { unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 8u8) as u8) } } @@ -665,6 +1229,31 @@ impl Date2 { } } #[inline] + pub unsafe fn byte_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 24usize, 8u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_byte_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 8u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( nWeekDay: ::std::os::raw::c_ushort, nMonthDay: ::std::os::raw::c_ushort, @@ -729,26 +1318,12 @@ pub struct Date3 { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, pub byte: ::std::os::raw::c_uchar, } -#[test] -fn bindgen_test_layout_Date3() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Date3)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(Date3)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).byte) as usize - ptr as usize }, - 3usize, - concat!("Offset of field: ", stringify!(Date3), "::", stringify!(byte)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Date3"][::std::mem::size_of::() - 4usize]; + ["Alignment of Date3"][::std::mem::align_of::() - 2usize]; + ["Offset of field: Date3::byte"][::std::mem::offset_of!(Date3, byte) - 3usize]; +}; impl Date3 { #[inline] pub fn nWeekDay(&self) -> ::std::os::raw::c_ushort { @@ -762,6 +1337,31 @@ impl Date3 { } } #[inline] + pub unsafe fn nWeekDay_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 3u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nWeekDay_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 3u8, + val as u64, + ) + } + } + #[inline] pub fn nMonthDay(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 6u8) as u16) } } @@ -773,6 +1373,31 @@ impl Date3 { } } #[inline] + pub unsafe fn nMonthDay_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 3usize, 6u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nMonthDay_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 6u8, + val as u64, + ) + } + } + #[inline] pub fn nMonth(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 5u8) as u16) } } @@ -784,6 +1409,31 @@ impl Date3 { } } #[inline] + pub unsafe fn nMonth_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 9usize, 5u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nMonth_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 5u8, + val as u64, + ) + } + } + #[inline] pub fn nYear(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 8u8) as u16) } } @@ -795,6 +1445,31 @@ impl Date3 { } } #[inline] + pub unsafe fn nYear_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 8u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_nYear_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 8u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( nWeekDay: ::std::os::raw::c_ushort, nMonthDay: ::std::os::raw::c_ushort, diff --git a/bindgen-tests/tests/expectations/tests/bitfield_align_2.rs b/bindgen-tests/tests/expectations/tests/bitfield_align_2.rs index 963d86f9be..2a676d5636 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield_align_2.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield_align_2.rs @@ -16,10 +16,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -29,21 +26,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -66,6 +90,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -83,6 +127,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] @@ -98,19 +160,11 @@ pub struct TaggedPtr { pub _bitfield_align_1: [u64; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } -#[test] -fn bindgen_test_layout_TaggedPtr() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(TaggedPtr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(TaggedPtr)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TaggedPtr"][::std::mem::size_of::() - 8usize]; + ["Alignment of TaggedPtr"][::std::mem::align_of::() - 8usize]; +}; impl Default for TaggedPtr { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -133,6 +187,31 @@ impl TaggedPtr { } } #[inline] + pub unsafe fn tag_raw(this: *const Self) -> MyEnum { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 2u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_tag_raw(this: *mut Self, val: MyEnum) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] pub fn ptr(&self) -> ::std::os::raw::c_long { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 62u8) as u64) } } @@ -144,6 +223,31 @@ impl TaggedPtr { } } #[inline] + pub unsafe fn ptr_raw(this: *const Self) -> ::std::os::raw::c_long { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 62u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_ptr_raw(this: *mut Self, val: ::std::os::raw::c_long) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 62u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( tag: MyEnum, ptr: ::std::os::raw::c_long, diff --git a/bindgen-tests/tests/expectations/tests/bitfield_large_overflow.rs b/bindgen-tests/tests/expectations/tests/bitfield_large_overflow.rs index 54f09f6229..51c777497b 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield_large_overflow.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield_large_overflow.rs @@ -5,19 +5,11 @@ pub struct _bindgen_ty_1 { pub _bindgen_opaque_blob: [u64; 10usize], } -#[test] -fn bindgen_test_layout__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::<_bindgen_ty_1>(), - 80usize, - concat!("Size of: ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::<_bindgen_ty_1>(), - 8usize, - concat!("Alignment of ", stringify!(_bindgen_ty_1)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of _bindgen_ty_1"][::std::mem::size_of::<_bindgen_ty_1>() - 80usize]; + ["Alignment of _bindgen_ty_1"][::std::mem::align_of::<_bindgen_ty_1>() - 8usize]; +}; +unsafe extern "C" { pub static mut a: _bindgen_ty_1; } diff --git a/bindgen-tests/tests/expectations/tests/bitfield_method_mangling.rs b/bindgen-tests/tests/expectations/tests/bitfield_method_mangling.rs index 7104682ea8..1a08cd00f9 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield_method_mangling.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield_method_mangling.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -89,19 +151,15 @@ pub struct mach_msg_type_descriptor_t { pub _bitfield_align_1: [u32; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, } -#[test] -fn bindgen_test_layout_mach_msg_type_descriptor_t() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(mach_msg_type_descriptor_t)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(mach_msg_type_descriptor_t)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of mach_msg_type_descriptor_t", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of mach_msg_type_descriptor_t", + ][::std::mem::align_of::() - 4usize]; +}; impl mach_msg_type_descriptor_t { #[inline] pub fn pad3(&self) -> ::std::os::raw::c_uint { @@ -115,6 +173,31 @@ impl mach_msg_type_descriptor_t { } } #[inline] + pub unsafe fn pad3_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 24u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_pad3_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 24u8, + val as u64, + ) + } + } + #[inline] pub fn type_(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 8u8) as u32) } } @@ -126,6 +209,31 @@ impl mach_msg_type_descriptor_t { } } #[inline] + pub unsafe fn type__raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 24usize, 8u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_type_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 8u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( pad3: ::std::os::raw::c_uint, type_: ::std::os::raw::c_uint, diff --git a/bindgen-tests/tests/expectations/tests/bitfield_pragma_packed.rs b/bindgen-tests/tests/expectations/tests/bitfield_pragma_packed.rs index e3168f51ea..8869593ed5 100644 --- a/bindgen-tests/tests/expectations/tests/bitfield_pragma_packed.rs +++ b/bindgen-tests/tests/expectations/tests/bitfield_pragma_packed.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -89,19 +151,11 @@ pub struct Struct { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, } -#[test] -fn bindgen_test_layout_Struct() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Struct)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Struct"][::std::mem::size_of::() - 4usize]; + ["Alignment of Struct"][::std::mem::align_of::() - 1usize]; +}; impl Struct { #[inline] pub fn a(&self) -> ::std::os::raw::c_uchar { @@ -115,6 +169,30 @@ impl Struct { } } #[inline] + pub unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b(&self) -> ::std::os::raw::c_uchar { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u8) } } @@ -126,6 +204,30 @@ impl Struct { } } #[inline] + pub unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn c(&self) -> ::std::os::raw::c_uchar { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 6u8) as u8) } } @@ -137,6 +239,30 @@ impl Struct { } } #[inline] + pub unsafe fn c_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 6u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_c_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 6u8, + val as u64, + ) + } + } + #[inline] pub fn d(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 16u8) as u16) } } @@ -148,6 +274,31 @@ impl Struct { } } #[inline] + pub unsafe fn d_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 8usize, 16u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_d_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 16u8, + val as u64, + ) + } + } + #[inline] pub fn e(&self) -> ::std::os::raw::c_uchar { unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 8u8) as u8) } } @@ -159,6 +310,31 @@ impl Struct { } } #[inline] + pub unsafe fn e_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 24usize, 8u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_e_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 8u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( a: ::std::os::raw::c_uchar, b: ::std::os::raw::c_uchar, @@ -221,19 +397,11 @@ pub struct Inner { pub _bitfield_align_1: [u16; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, } -#[test] -fn bindgen_test_layout_Inner() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Inner)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(Inner)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Inner"][::std::mem::size_of::() - 4usize]; + ["Alignment of Inner"][::std::mem::align_of::() - 2usize]; +}; impl Inner { #[inline] pub fn a(&self) -> ::std::os::raw::c_ushort { @@ -247,6 +415,31 @@ impl Inner { } } #[inline] + pub unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 16u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] pub fn b(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u16) } } @@ -258,6 +451,31 @@ impl Inner { } } #[inline] + pub unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 16u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( a: ::std::os::raw::c_ushort, b: ::std::os::raw::c_ushort, @@ -289,23 +507,9 @@ impl Inner { pub struct Outer { pub inner: Inner, } -#[test] -fn bindgen_test_layout_Outer() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Outer)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Outer)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).inner) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Outer), "::", stringify!(inner)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Outer"][::std::mem::size_of::() - 4usize]; + ["Alignment of Outer"][::std::mem::align_of::() - 1usize]; + ["Offset of field: Outer::inner"][::std::mem::offset_of!(Outer, inner) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/block_return_type.rs b/bindgen-tests/tests/expectations/tests/block_return_type.rs index fa6c0ac67c..8ab2d70f11 100644 --- a/bindgen-tests/tests/expectations/tests/block_return_type.rs +++ b/bindgen-tests/tests/expectations/tests/block_return_type.rs @@ -1,7 +1,7 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #![cfg(target_os = "macos")] extern crate block; -extern "C" { +unsafe extern "C" { pub fn func() -> _bindgen_ty_id_4; } pub type _bindgen_ty_id_4 = *const ::block::Block< diff --git a/bindgen-tests/tests/expectations/tests/blocklist-and-impl-debug.rs b/bindgen-tests/tests/expectations/tests/blocklist-and-impl-debug.rs index c09ff915b7..43e645bfc3 100644 --- a/bindgen-tests/tests/expectations/tests/blocklist-and-impl-debug.rs +++ b/bindgen-tests/tests/expectations/tests/blocklist-and-impl-debug.rs @@ -5,31 +5,18 @@ pub struct BlocklistMe(u8); pub struct ShouldManuallyImplDebug { pub a: BlocklistMe, } -#[test] -fn bindgen_test_layout_ShouldManuallyImplDebug() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ShouldManuallyImplDebug)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ShouldManuallyImplDebug)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldManuallyImplDebug), - "::", - stringify!(a), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ShouldManuallyImplDebug", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of ShouldManuallyImplDebug", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ShouldManuallyImplDebug::a", + ][::std::mem::offset_of!(ShouldManuallyImplDebug, a) - 0usize]; +}; impl Default for ShouldManuallyImplDebug { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/blocklist-file.rs b/bindgen-tests/tests/expectations/tests/blocklist-file.rs index 99f81f9e50..4056ef4d2c 100644 --- a/bindgen-tests/tests/expectations/tests/blocklist-file.rs +++ b/bindgen-tests/tests/expectations/tests/blocklist-file.rs @@ -6,63 +6,34 @@ pub struct SizedIntegers { pub y: u16, pub z: u32, } -#[test] -fn bindgen_test_layout_SizedIntegers() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(SizedIntegers)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(SizedIntegers)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(SizedIntegers), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 2usize, - concat!("Offset of field: ", stringify!(SizedIntegers), "::", stringify!(y)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).z) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(SizedIntegers), "::", stringify!(z)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of SizedIntegers"][::std::mem::size_of::() - 8usize]; + ["Alignment of SizedIntegers"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: SizedIntegers::x", + ][::std::mem::offset_of!(SizedIntegers, x) - 0usize]; + [ + "Offset of field: SizedIntegers::y", + ][::std::mem::offset_of!(SizedIntegers, y) - 2usize]; + [ + "Offset of field: SizedIntegers::z", + ][::std::mem::offset_of!(SizedIntegers, z) - 4usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct StructWithBlocklistedFwdDecl { pub b: u8, } -#[test] -fn bindgen_test_layout_StructWithBlocklistedFwdDecl() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(StructWithBlocklistedFwdDecl)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(StructWithBlocklistedFwdDecl)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(StructWithBlocklistedFwdDecl), - "::", - stringify!(b), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of StructWithBlocklistedFwdDecl", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of StructWithBlocklistedFwdDecl", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: StructWithBlocklistedFwdDecl::b", + ][::std::mem::offset_of!(StructWithBlocklistedFwdDecl, b) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/blocklist-function.rs b/bindgen-tests/tests/expectations/tests/blocklist-function.rs index 531ba2e6d8..65b66b2ac2 100644 --- a/bindgen-tests/tests/expectations/tests/blocklist-function.rs +++ b/bindgen-tests/tests/expectations/tests/blocklist-function.rs @@ -10,7 +10,7 @@ pub mod root { pub mod bar { #[allow(unused_imports)] use self::super::super::root; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN3bar18NamespacedFunctionEv"] pub fn NamespacedFunction(); } @@ -20,17 +20,9 @@ pub mod root { pub struct C { pub _address: u8, } - #[test] - fn bindgen_test_layout_C() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(C)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(C)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of C"][::std::mem::size_of::() - 1usize]; + ["Alignment of C"][::std::mem::align_of::() - 1usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/blocklist-item.rs b/bindgen-tests/tests/expectations/tests/blocklist-item.rs index 39de8002b3..c5daf050a1 100644 --- a/bindgen-tests/tests/expectations/tests/blocklist-item.rs +++ b/bindgen-tests/tests/expectations/tests/blocklist-item.rs @@ -10,7 +10,7 @@ pub mod root { pub mod bar { #[allow(unused_imports)] use self::super::super::root; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN3bar18NamespacedFunctionEv"] pub fn NamespacedFunction(); } diff --git a/bindgen-tests/tests/expectations/tests/blocklist-methods.rs b/bindgen-tests/tests/expectations/tests/blocklist-methods.rs index 583beabeed..c89cadb3d5 100644 --- a/bindgen-tests/tests/expectations/tests/blocklist-methods.rs +++ b/bindgen-tests/tests/expectations/tests/blocklist-methods.rs @@ -4,20 +4,12 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo3fooEv"] pub fn Foo_foo(this: *mut Foo) -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/blocklist_bitfield_unit.rs b/bindgen-tests/tests/expectations/tests/blocklist_bitfield_unit.rs new file mode 100644 index 0000000000..fc9f9a38c7 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/blocklist_bitfield_unit.rs @@ -0,0 +1,119 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[path = "./struct_with_bitfields.rs"] +mod bitfields; +use bitfields::*; +#[repr(C)] +#[derive(Debug, Default, Copy, Clone)] +pub struct C { + pub x: ::std::os::raw::c_uchar, + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, + pub baz: ::std::os::raw::c_uint, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 8usize]; + ["Alignment of C"][::std::mem::align_of::() - 4usize]; + ["Offset of field: C::x"][::std::mem::offset_of!(C, x) - 0usize]; + ["Offset of field: C::baz"][::std::mem::offset_of!(C, baz) - 4usize]; +}; +impl C { + #[inline] + pub fn b1(&self) -> ::std::os::raw::c_uint { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_b1(&mut self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn b1_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b1_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn b2(&self) -> ::std::os::raw::c_uint { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_b2(&mut self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn b2_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b2_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + b1: ::std::os::raw::c_uint, + b2: ::std::os::raw::c_uint, + ) -> __BindgenBitfieldUnit<[u8; 1usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); + __bindgen_bitfield_unit + .set( + 0usize, + 1u8, + { + let b1: u32 = unsafe { ::std::mem::transmute(b1) }; + b1 as u64 + }, + ); + __bindgen_bitfield_unit + .set( + 1usize, + 1u8, + { + let b2: u32 = unsafe { ::std::mem::transmute(b2) }; + b2 as u64 + }, + ); + __bindgen_bitfield_unit + } +} diff --git a/bindgen-tests/tests/expectations/tests/blocks-signature.rs b/bindgen-tests/tests/expectations/tests/blocks-signature.rs index 3f4fa289b0..93cf28e009 100644 --- a/bindgen-tests/tests/expectations/tests/blocks-signature.rs +++ b/bindgen-tests/tests/expectations/tests/blocks-signature.rs @@ -1,24 +1,24 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #![cfg(target_os = "macos")] extern crate block; -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z8atexit_bU13block_pointerFvvE"] pub fn atexit_b(arg1: _bindgen_ty_id_33); } pub type dispatch_data_t = *mut ::std::os::raw::c_void; pub type dispatch_data_applier_t = _bindgen_ty_id_40; -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z19dispatch_data_applyPvU13block_pointerFbS_yPKvyE"] pub fn dispatch_data_apply( data: dispatch_data_t, applier: dispatch_data_applier_t, ) -> bool; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z3fooU13block_pointerFvyE"] pub fn foo(arg1: _bindgen_ty_id_50) -> bool; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z7foo_ptrPU13block_pointerFvyE"] pub fn foo_ptr(arg1: *mut _bindgen_ty_id_56) -> bool; } @@ -28,41 +28,21 @@ pub struct contains_block_pointers { pub val: contains_block_pointers__bindgen_ty_id_61, pub ptr_val: *mut _bindgen_ty_id_68, } -#[test] -fn bindgen_test_layout_contains_block_pointers() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(contains_block_pointers)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(contains_block_pointers)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).val) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(contains_block_pointers), - "::", - stringify!(val), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ptr_val) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(contains_block_pointers), - "::", - stringify!(ptr_val), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of contains_block_pointers", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of contains_block_pointers", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: contains_block_pointers::val", + ][::std::mem::offset_of!(contains_block_pointers, val) - 0usize]; + [ + "Offset of field: contains_block_pointers::ptr_val", + ][::std::mem::offset_of!(contains_block_pointers, ptr_val) - 8usize]; +}; impl Default for contains_block_pointers { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/blocks.rs b/bindgen-tests/tests/expectations/tests/blocks.rs index 0d43e65fc4..4f51113c4b 100644 --- a/bindgen-tests/tests/expectations/tests/blocks.rs +++ b/bindgen-tests/tests/expectations/tests/blocks.rs @@ -1,23 +1,23 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #![cfg(target_os = "macos")] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z8atexit_bU13block_pointerFvvE"] pub fn atexit_b(arg1: *mut ::std::os::raw::c_void); } pub type dispatch_data_t = *mut ::std::os::raw::c_void; pub type dispatch_data_applier_t = *mut ::std::os::raw::c_void; -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z19dispatch_data_applyPvU13block_pointerFbS_yPKvyE"] pub fn dispatch_data_apply( data: dispatch_data_t, applier: dispatch_data_applier_t, ) -> bool; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z3fooU13block_pointerFvyE"] pub fn foo(arg1: *mut ::std::os::raw::c_void) -> bool; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z7foo_ptrPU13block_pointerFvyE"] pub fn foo_ptr(arg1: *mut *mut ::std::os::raw::c_void) -> bool; } @@ -27,41 +27,21 @@ pub struct contains_block_pointers { pub val: *mut ::std::os::raw::c_void, pub ptr_val: *mut *mut ::std::os::raw::c_void, } -#[test] -fn bindgen_test_layout_contains_block_pointers() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(contains_block_pointers)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(contains_block_pointers)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).val) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(contains_block_pointers), - "::", - stringify!(val), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ptr_val) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(contains_block_pointers), - "::", - stringify!(ptr_val), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of contains_block_pointers", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of contains_block_pointers", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: contains_block_pointers::val", + ][::std::mem::offset_of!(contains_block_pointers, val) - 0usize]; + [ + "Offset of field: contains_block_pointers::ptr_val", + ][::std::mem::offset_of!(contains_block_pointers, ptr_val) - 8usize]; +}; impl Default for contains_block_pointers { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/bug-1529681.rs b/bindgen-tests/tests/expectations/tests/bug-1529681.rs index 50d48d438c..bd59c1971f 100644 --- a/bindgen-tests/tests/expectations/tests/bug-1529681.rs +++ b/bindgen-tests/tests/expectations/tests/bug-1529681.rs @@ -4,16 +4,8 @@ pub struct BrowsingContext { pub _address: u8, } -#[test] -fn bindgen_test_layout_BrowsingContext() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(BrowsingContext)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(BrowsingContext)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of BrowsingContext"][::std::mem::size_of::() - 1usize]; + ["Alignment of BrowsingContext"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/c-empty-layout.rs b/bindgen-tests/tests/expectations/tests/c-empty-layout.rs index 7d59cadcca..709a9a59d8 100644 --- a/bindgen-tests/tests/expectations/tests/c-empty-layout.rs +++ b/bindgen-tests/tests/expectations/tests/c-empty-layout.rs @@ -2,16 +2,8 @@ #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Foo {} -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 0usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/c-unwind-abi-override.rs b/bindgen-tests/tests/expectations/tests/c-unwind-abi-override.rs index 25fd333cea..a158565033 100644 --- a/bindgen-tests/tests/expectations/tests/c-unwind-abi-override.rs +++ b/bindgen-tests/tests/expectations/tests/c-unwind-abi-override.rs @@ -1,10 +1,10 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C-unwind" { +unsafe extern "C-unwind" { pub fn foo(); } -extern "C-unwind" { +unsafe extern "C-unwind" { pub fn bar(); } -extern "C" { +unsafe extern "C" { pub fn baz(); } diff --git a/bindgen-tests/tests/expectations/tests/c_naming.rs b/bindgen-tests/tests/expectations/tests/c_naming.rs index a88f1b3572..38e63ce874 100644 --- a/bindgen-tests/tests/expectations/tests/c_naming.rs +++ b/bindgen-tests/tests/expectations/tests/c_naming.rs @@ -4,26 +4,12 @@ pub struct struct_a { pub a: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_struct_a() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(struct_a)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(struct_a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(struct_a), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of struct_a"][::std::mem::size_of::() - 4usize]; + ["Alignment of struct_a"][::std::mem::align_of::() - 4usize]; + ["Offset of field: struct_a::a"][::std::mem::offset_of!(struct_a, a) - 0usize]; +}; pub type a = *const struct_a; #[repr(C)] #[derive(Copy, Clone)] @@ -31,31 +17,13 @@ pub union union_b { pub a: ::std::os::raw::c_int, pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_union_b() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(union_b)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(union_b)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(union_b), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(union_b), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of union_b"][::std::mem::size_of::() - 4usize]; + ["Alignment of union_b"][::std::mem::align_of::() - 4usize]; + ["Offset of field: union_b::a"][::std::mem::offset_of!(union_b, a) - 0usize]; + ["Offset of field: union_b::b"][::std::mem::offset_of!(union_b, b) - 0usize]; +}; impl Default for union_b { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -68,12 +36,12 @@ impl Default for union_b { pub type b = union_b; pub const enum_c_A: enum_c = 0; pub type enum_c = ::std::os::raw::c_uint; -extern "C" { +unsafe extern "C" { pub fn takes_a(arg: a); } -extern "C" { +unsafe extern "C" { pub fn takes_b(arg: b); } -extern "C" { +unsafe extern "C" { pub fn takes_c(arg: enum_c); } diff --git a/bindgen-tests/tests/expectations/tests/call-conv-field.rs b/bindgen-tests/tests/expectations/tests/call-conv-field.rs index e3179543fc..8f0502a435 100644 --- a/bindgen-tests/tests/expectations/tests/call-conv-field.rs +++ b/bindgen-tests/tests/expectations/tests/call-conv-field.rs @@ -10,41 +10,21 @@ pub struct JNINativeInterface_ { >, pub __hack: ::std::os::raw::c_ulonglong, } -#[test] -fn bindgen_test_layout_JNINativeInterface_() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(JNINativeInterface_)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(JNINativeInterface_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).GetVersion) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(JNINativeInterface_), - "::", - stringify!(GetVersion), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).__hack) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(JNINativeInterface_), - "::", - stringify!(__hack), - ), - ); -} -extern "stdcall" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of JNINativeInterface_", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of JNINativeInterface_", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: JNINativeInterface_::GetVersion", + ][::std::mem::offset_of!(JNINativeInterface_, GetVersion) - 0usize]; + [ + "Offset of field: JNINativeInterface_::__hack", + ][::std::mem::offset_of!(JNINativeInterface_, __hack) - 8usize]; +}; +unsafe extern "stdcall" { pub fn bar(); } diff --git a/bindgen-tests/tests/expectations/tests/canonical-types.rs b/bindgen-tests/tests/expectations/tests/canonical-types.rs index d19ced3b43..81d2e488a2 100644 --- a/bindgen-tests/tests/expectations/tests/canonical-types.rs +++ b/bindgen-tests/tests/expectations/tests/canonical-types.rs @@ -7,8 +7,8 @@ pub struct ClassA { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct ClassA_ClassAInner { - pub x: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub x: *mut T, } impl Default for ClassA_ClassAInner { fn default() -> Self { @@ -76,19 +76,11 @@ impl Default for ClassC_ClassCInnerCRTP { pub struct ClassD { pub _address: u8, } -#[test] -fn bindgen_test_layout_ClassD() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ClassD)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ClassD)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ClassD"][::std::mem::size_of::() - 1usize]; + ["Alignment of ClassD"][::std::mem::align_of::() - 1usize]; +}; impl Default for ClassD { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -98,37 +90,25 @@ impl Default for ClassD { } } } -#[test] -fn __bindgen_test_layout_ClassB_open0_ClassD_ClassCInnerCRTP_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(ClassB)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(ClassB)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: ClassB_open0_ClassD_ClassCInnerCRTP_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: ClassB_open0_ClassD_ClassCInnerCRTP_close0", + ][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct ClassCInnerCRTP { pub _address: u8, } -#[test] -fn bindgen_test_layout_ClassCInnerCRTP() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ClassCInnerCRTP)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ClassCInnerCRTP)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ClassCInnerCRTP"][::std::mem::size_of::() - 1usize]; + ["Alignment of ClassCInnerCRTP"][::std::mem::align_of::() - 1usize]; +}; impl Default for ClassCInnerCRTP { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -138,44 +118,26 @@ impl Default for ClassCInnerCRTP { } } } -#[test] -fn __bindgen_test_layout_ClassB_open0_ClassCInnerCRTP_ClassAInner_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(ClassB)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(ClassB)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: ClassB_open0_ClassCInnerCRTP_ClassAInner_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: ClassB_open0_ClassCInnerCRTP_ClassAInner_close0", + ][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct ClassAInner { pub x: *mut ClassCInnerA, } -#[test] -fn bindgen_test_layout_ClassAInner() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(ClassAInner)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ClassAInner)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(ClassAInner), "::", stringify!(x)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ClassAInner"][::std::mem::size_of::() - 8usize]; + ["Alignment of ClassAInner"][::std::mem::align_of::() - 8usize]; + ["Offset of field: ClassAInner::x"][::std::mem::offset_of!(ClassAInner, x) - 0usize]; +}; impl Default for ClassAInner { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -190,26 +152,14 @@ impl Default for ClassAInner { pub struct ClassCInnerA { pub member: *mut ClassCInnerB, } -#[test] -fn bindgen_test_layout_ClassCInnerA() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(ClassCInnerA)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ClassCInnerA)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(ClassCInnerA), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ClassCInnerA"][::std::mem::size_of::() - 8usize]; + ["Alignment of ClassCInnerA"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: ClassCInnerA::member", + ][::std::mem::offset_of!(ClassCInnerA, member) - 0usize]; +}; impl Default for ClassCInnerA { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -224,26 +174,14 @@ impl Default for ClassCInnerA { pub struct ClassCInnerB { pub cache: *mut ClassCInnerA, } -#[test] -fn bindgen_test_layout_ClassCInnerB() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(ClassCInnerB)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ClassCInnerB)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cache) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(ClassCInnerB), "::", stringify!(cache)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ClassCInnerB"][::std::mem::size_of::() - 8usize]; + ["Alignment of ClassCInnerB"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: ClassCInnerB::cache", + ][::std::mem::offset_of!(ClassCInnerB, cache) - 0usize]; +}; impl Default for ClassCInnerB { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/canonical_path_without_namespacing.rs b/bindgen-tests/tests/expectations/tests/canonical_path_without_namespacing.rs index 11ae02814e..613da3060f 100644 --- a/bindgen-tests/tests/expectations/tests/canonical_path_without_namespacing.rs +++ b/bindgen-tests/tests/expectations/tests/canonical_path_without_namespacing.rs @@ -4,20 +4,12 @@ pub struct Bar { pub _address: u8, } -#[test] -fn bindgen_test_layout_Bar() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Bar)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_Z3bazPN3foo3BarE"] pub fn baz(arg1: *mut Bar); } diff --git a/bindgen-tests/tests/expectations/tests/char.rs b/bindgen-tests/tests/expectations/tests/char.rs index f3acf04e0c..61a81269d7 100644 --- a/bindgen-tests/tests/expectations/tests/char.rs +++ b/bindgen-tests/tests/expectations/tests/char.rs @@ -18,78 +18,20 @@ pub struct Test { pub Ccu: UChar, pub Ccd: SChar, } -#[test] -fn bindgen_test_layout_Test() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(Test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Test)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ch) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(ch)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 1usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(u)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 2usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(d)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cch) as usize - ptr as usize }, - 3usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cch)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cu) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cu)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cd) as usize - ptr as usize }, - 5usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cd)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cch) as usize - ptr as usize }, - 6usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cch)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cu) as usize - ptr as usize }, - 7usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cu)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cd) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cd)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccch) as usize - ptr as usize }, - 9usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Ccch)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccu) as usize - ptr as usize }, - 10usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Ccu)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccd) as usize - ptr as usize }, - 11usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Ccd)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 12usize]; + ["Alignment of Test"][::std::mem::align_of::() - 1usize]; + ["Offset of field: Test::ch"][::std::mem::offset_of!(Test, ch) - 0usize]; + ["Offset of field: Test::u"][::std::mem::offset_of!(Test, u) - 1usize]; + ["Offset of field: Test::d"][::std::mem::offset_of!(Test, d) - 2usize]; + ["Offset of field: Test::cch"][::std::mem::offset_of!(Test, cch) - 3usize]; + ["Offset of field: Test::cu"][::std::mem::offset_of!(Test, cu) - 4usize]; + ["Offset of field: Test::cd"][::std::mem::offset_of!(Test, cd) - 5usize]; + ["Offset of field: Test::Cch"][::std::mem::offset_of!(Test, Cch) - 6usize]; + ["Offset of field: Test::Cu"][::std::mem::offset_of!(Test, Cu) - 7usize]; + ["Offset of field: Test::Cd"][::std::mem::offset_of!(Test, Cd) - 8usize]; + ["Offset of field: Test::Ccch"][::std::mem::offset_of!(Test, Ccch) - 9usize]; + ["Offset of field: Test::Ccu"][::std::mem::offset_of!(Test, Ccu) - 10usize]; + ["Offset of field: Test::Ccd"][::std::mem::offset_of!(Test, Ccd) - 11usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/char16_t.rs b/bindgen-tests/tests/expectations/tests/char16_t.rs new file mode 100644 index 0000000000..82d30fe517 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/char16_t.rs @@ -0,0 +1,7 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(transparent)] +pub struct bindgen_cchar16_t(u16); +unsafe extern "C" { + #[link_name = "\u{1}_Z16receive_char16_tDs"] + pub fn receive_char16_t(input: bindgen_cchar16_t); +} diff --git a/bindgen-tests/tests/expectations/tests/class.rs b/bindgen-tests/tests/expectations/tests/class.rs index 19668a73dd..69591d1bce 100644 --- a/bindgen-tests/tests/expectations/tests/class.rs +++ b/bindgen-tests/tests/expectations/tests/class.rs @@ -39,21 +39,17 @@ pub struct C { fn bindgen_test_layout_C() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 40usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); + assert_eq!(::std::mem::size_of::(), 40usize, "Size of C"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of C"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(a)), + "Offset of field: C::a", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).big_array) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(big_array)), + "Offset of field: C::big_array", ); } impl Default for C { @@ -78,44 +74,29 @@ fn bindgen_test_layout_C_with_zero_length_array() { assert_eq!( ::std::mem::size_of::(), 40usize, - concat!("Size of: ", stringify!(C_with_zero_length_array)), + "Size of C_with_zero_length_array", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(C_with_zero_length_array)), + "Alignment of C_with_zero_length_array", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array), - "::", - stringify!(a), - ), + "Offset of field: C_with_zero_length_array::a", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).big_array) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array), - "::", - stringify!(big_array), - ), + "Offset of field: C_with_zero_length_array::big_array", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize }, 37usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array), - "::", - stringify!(zero_length_array), - ), + "Offset of field: C_with_zero_length_array::zero_length_array", ); } impl Default for C_with_zero_length_array { @@ -140,34 +121,24 @@ fn bindgen_test_layout_C_with_zero_length_array_2() { assert_eq!( ::std::mem::size_of::(), 4usize, - concat!("Size of: ", stringify!(C_with_zero_length_array_2)), + "Size of C_with_zero_length_array_2", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(C_with_zero_length_array_2)), + "Alignment of C_with_zero_length_array_2", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_2), - "::", - stringify!(a), - ), + "Offset of field: C_with_zero_length_array_2::a", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_2), - "::", - stringify!(zero_length_array), - ), + "Offset of field: C_with_zero_length_array_2::zero_length_array", ); } #[repr(C)] @@ -183,42 +154,27 @@ fn bindgen_test_layout_C_with_incomplete_array() { assert_eq!( ::std::mem::size_of::(), 40usize, - concat!("Size of: ", stringify!(C_with_incomplete_array)), + "Size of C_with_incomplete_array", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(C_with_incomplete_array)), + "Alignment of C_with_incomplete_array", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array), - "::", - stringify!(a), - ), + "Offset of field: C_with_incomplete_array::a", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).big_array) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array), - "::", - stringify!(big_array), - ), + "Offset of field: C_with_incomplete_array::big_array", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, 37usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array), - "::", - stringify!(incomplete_array), - ), + "Offset of field: C_with_incomplete_array::incomplete_array", ); } impl Default for C_with_incomplete_array { @@ -243,32 +199,22 @@ fn bindgen_test_layout_C_with_incomplete_array_2() { assert_eq!( ::std::mem::size_of::(), 4usize, - concat!("Size of: ", stringify!(C_with_incomplete_array_2)), + "Size of C_with_incomplete_array_2", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(C_with_incomplete_array_2)), + "Alignment of C_with_incomplete_array_2", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array_2), - "::", - stringify!(a), - ), + "Offset of field: C_with_incomplete_array_2::a", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array_2), - "::", - stringify!(incomplete_array), - ), + "Offset of field: C_with_incomplete_array_2::incomplete_array", ); } #[repr(C)] @@ -287,57 +233,34 @@ fn bindgen_test_layout_C_with_zero_length_array_and_incomplete_array() { assert_eq!( ::std::mem::size_of::(), 40usize, - concat!("Size of: ", stringify!(C_with_zero_length_array_and_incomplete_array)), + "Size of C_with_zero_length_array_and_incomplete_array", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!( - "Alignment of ", - stringify!(C_with_zero_length_array_and_incomplete_array), - ), + "Alignment of C_with_zero_length_array_and_incomplete_array", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array), - "::", - stringify!(a), - ), + "Offset of field: C_with_zero_length_array_and_incomplete_array::a", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).big_array) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array), - "::", - stringify!(big_array), - ), + "Offset of field: C_with_zero_length_array_and_incomplete_array::big_array", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize }, 37usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array), - "::", - stringify!(zero_length_array), - ), + "Offset of field: C_with_zero_length_array_and_incomplete_array::zero_length_array", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, 37usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array), - "::", - stringify!(incomplete_array), - ), + "Offset of field: C_with_zero_length_array_and_incomplete_array::incomplete_array", ); } impl Default for C_with_zero_length_array_and_incomplete_array { @@ -365,47 +288,29 @@ fn bindgen_test_layout_C_with_zero_length_array_and_incomplete_array_2() { assert_eq!( ::std::mem::size_of::(), 4usize, - concat!("Size of: ", stringify!(C_with_zero_length_array_and_incomplete_array_2)), + "Size of C_with_zero_length_array_and_incomplete_array_2", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!( - "Alignment of ", - stringify!(C_with_zero_length_array_and_incomplete_array_2), - ), + "Alignment of C_with_zero_length_array_and_incomplete_array_2", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array_2), - "::", - stringify!(a), - ), + "Offset of field: C_with_zero_length_array_and_incomplete_array_2::a", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array_2), - "::", - stringify!(zero_length_array), - ), + "Offset of field: C_with_zero_length_array_and_incomplete_array_2::zero_length_array", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array_2), - "::", - stringify!(incomplete_array), - ), + "Offset of field: C_with_zero_length_array_and_incomplete_array_2::incomplete_array", ); } #[repr(C)] @@ -417,20 +322,12 @@ pub struct WithDtor { fn bindgen_test_layout_WithDtor() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithDtor)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithDtor)), - ); + assert_eq!(::std::mem::size_of::(), 4usize, "Size of WithDtor"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of WithDtor"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(WithDtor), "::", stringify!(b)), + "Offset of field: WithDtor::b", ); } #[repr(C)] @@ -445,32 +342,22 @@ fn bindgen_test_layout_IncompleteArrayNonCopiable() { assert_eq!( ::std::mem::size_of::(), 8usize, - concat!("Size of: ", stringify!(IncompleteArrayNonCopiable)), + "Size of IncompleteArrayNonCopiable", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(IncompleteArrayNonCopiable)), + "Alignment of IncompleteArrayNonCopiable", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).whatever) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(IncompleteArrayNonCopiable), - "::", - stringify!(whatever), - ), + "Offset of field: IncompleteArrayNonCopiable::whatever", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(IncompleteArrayNonCopiable), - "::", - stringify!(incomplete_array), - ), + "Offset of field: IncompleteArrayNonCopiable::incomplete_array", ); } impl Default for IncompleteArrayNonCopiable { @@ -492,25 +379,17 @@ pub union Union { fn bindgen_test_layout_Union() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Union)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Union)), - ); + assert_eq!(::std::mem::size_of::(), 4usize, "Size of Union"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of Union"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Union), "::", stringify!(d)), + "Offset of field: Union::d", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Union), "::", stringify!(i)), + "Offset of field: Union::i", ); } impl Default for Union { @@ -531,20 +410,12 @@ pub struct WithUnion { fn bindgen_test_layout_WithUnion() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithUnion)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithUnion)), - ); + assert_eq!(::std::mem::size_of::(), 4usize, "Size of WithUnion"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of WithUnion"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).data) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(WithUnion), "::", stringify!(data)), + "Offset of field: WithUnion::data", ); } impl Default for WithUnion { @@ -566,12 +437,12 @@ fn bindgen_test_layout_RealAbstractionWithTonsOfMethods() { assert_eq!( ::std::mem::size_of::(), 1usize, - concat!("Size of: ", stringify!(RealAbstractionWithTonsOfMethods)), + "Size of RealAbstractionWithTonsOfMethods", ); assert_eq!( ::std::mem::align_of::(), 1usize, - concat!("Alignment of ", stringify!(RealAbstractionWithTonsOfMethods)), + "Alignment of RealAbstractionWithTonsOfMethods", ); } extern "C" { diff --git a/bindgen-tests/tests/expectations/tests/class_1_0.rs b/bindgen-tests/tests/expectations/tests/class_1_0.rs deleted file mode 100644 index b6544212cf..0000000000 --- a/bindgen-tests/tests/expectations/tests/class_1_0.rs +++ /dev/null @@ -1,668 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Default)] -pub struct __IncompleteArrayField(::std::marker::PhantomData, [T; 0]); -impl __IncompleteArrayField { - #[inline] - pub fn new() -> Self { - __IncompleteArrayField(::std::marker::PhantomData, []) - } - #[inline] - pub fn as_ptr(&self) -> *const T { - self as *const _ as *const T - } - #[inline] - pub fn as_mut_ptr(&mut self) -> *mut T { - self as *mut _ as *mut T - } - #[inline] - pub unsafe fn as_slice(&self, len: usize) -> &[T] { - ::std::slice::from_raw_parts(self.as_ptr(), len) - } - #[inline] - pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { - ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) - } -} -impl ::std::fmt::Debug for __IncompleteArrayField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__IncompleteArrayField") - } -} -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Copy)] -pub struct C { - pub a: ::std::os::raw::c_int, - pub big_array: [::std::os::raw::c_char; 33usize], -} -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 40usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).big_array) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(big_array)), - ); -} -impl Clone for C { - fn clone(&self) -> Self { - *self - } -} -impl Default for C { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -impl ::std::cmp::PartialEq for C { - fn eq(&self, other: &C) -> bool { - self.a == other.a && &self.big_array[..] == &other.big_array[..] - } -} -#[repr(C)] -pub struct C_with_zero_length_array { - pub a: ::std::os::raw::c_int, - pub big_array: [::std::os::raw::c_char; 33usize], - pub zero_length_array: __IncompleteArrayField<::std::os::raw::c_char>, -} -#[test] -fn bindgen_test_layout_C_with_zero_length_array() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 40usize, - concat!("Size of: ", stringify!(C_with_zero_length_array)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C_with_zero_length_array)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).big_array) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array), - "::", - stringify!(big_array), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize - }, - 37usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array), - "::", - stringify!(zero_length_array), - ), - ); -} -impl Default for C_with_zero_length_array { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default)] -pub struct C_with_zero_length_array_2 { - pub a: ::std::os::raw::c_int, - pub zero_length_array: __IncompleteArrayField<::std::os::raw::c_char>, -} -#[test] -fn bindgen_test_layout_C_with_zero_length_array_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(C_with_zero_length_array_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C_with_zero_length_array_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_2), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize - }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_2), - "::", - stringify!(zero_length_array), - ), - ); -} -#[repr(C)] -pub struct C_with_incomplete_array { - pub a: ::std::os::raw::c_int, - pub big_array: [::std::os::raw::c_char; 33usize], - pub incomplete_array: __IncompleteArrayField<::std::os::raw::c_char>, -} -#[test] -fn bindgen_test_layout_C_with_incomplete_array() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 40usize, - concat!("Size of: ", stringify!(C_with_incomplete_array)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C_with_incomplete_array)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).big_array) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array), - "::", - stringify!(big_array), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, - 37usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array), - "::", - stringify!(incomplete_array), - ), - ); -} -impl Default for C_with_incomplete_array { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default)] -pub struct C_with_incomplete_array_2 { - pub a: ::std::os::raw::c_int, - pub incomplete_array: __IncompleteArrayField<::std::os::raw::c_char>, -} -#[test] -fn bindgen_test_layout_C_with_incomplete_array_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(C_with_incomplete_array_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C_with_incomplete_array_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array_2), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_incomplete_array_2), - "::", - stringify!(incomplete_array), - ), - ); -} -#[repr(C)] -pub struct C_with_zero_length_array_and_incomplete_array { - pub a: ::std::os::raw::c_int, - pub big_array: [::std::os::raw::c_char; 33usize], - pub zero_length_array: __IncompleteArrayField<::std::os::raw::c_char>, - pub incomplete_array: __IncompleteArrayField<::std::os::raw::c_char>, -} -#[test] -fn bindgen_test_layout_C_with_zero_length_array_and_incomplete_array() { - const UNINIT: ::std::mem::MaybeUninit< - C_with_zero_length_array_and_incomplete_array, - > = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 40usize, - concat!("Size of: ", stringify!(C_with_zero_length_array_and_incomplete_array)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!( - "Alignment of ", - stringify!(C_with_zero_length_array_and_incomplete_array), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).big_array) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array), - "::", - stringify!(big_array), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize - }, - 37usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array), - "::", - stringify!(zero_length_array), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, - 37usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array), - "::", - stringify!(incomplete_array), - ), - ); -} -impl Default for C_with_zero_length_array_and_incomplete_array { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default)] -pub struct C_with_zero_length_array_and_incomplete_array_2 { - pub a: ::std::os::raw::c_int, - pub zero_length_array: __IncompleteArrayField<::std::os::raw::c_char>, - pub incomplete_array: __IncompleteArrayField<::std::os::raw::c_char>, -} -#[test] -fn bindgen_test_layout_C_with_zero_length_array_and_incomplete_array_2() { - const UNINIT: ::std::mem::MaybeUninit< - C_with_zero_length_array_and_incomplete_array_2, - > = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(C_with_zero_length_array_and_incomplete_array_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!( - "Alignment of ", - stringify!(C_with_zero_length_array_and_incomplete_array_2), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array_2), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize - }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array_2), - "::", - stringify!(zero_length_array), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C_with_zero_length_array_and_incomplete_array_2), - "::", - stringify!(incomplete_array), - ), - ); -} -#[repr(C)] -#[derive(Debug, Default, Hash, PartialEq, Eq)] -pub struct WithDtor { - pub b: ::std::os::raw::c_int, -} -#[test] -fn bindgen_test_layout_WithDtor() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithDtor)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithDtor)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithDtor), "::", stringify!(b)), - ); -} -#[repr(C)] -pub struct IncompleteArrayNonCopiable { - pub whatever: *mut ::std::os::raw::c_void, - pub incomplete_array: __IncompleteArrayField, -} -#[test] -fn bindgen_test_layout_IncompleteArrayNonCopiable() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(IncompleteArrayNonCopiable)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(IncompleteArrayNonCopiable)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).whatever) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(IncompleteArrayNonCopiable), - "::", - stringify!(whatever), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(IncompleteArrayNonCopiable), - "::", - stringify!(incomplete_array), - ), - ); -} -impl Default for IncompleteArrayNonCopiable { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq)] -pub struct Union { - pub d: __BindgenUnionField, - pub i: __BindgenUnionField<::std::os::raw::c_int>, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_Union() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Union)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Union)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Union), "::", stringify!(d)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Union), "::", stringify!(i)), - ); -} -impl Clone for Union { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq)] -pub struct WithUnion { - pub data: Union, -} -#[test] -fn bindgen_test_layout_WithUnion() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithUnion)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithUnion)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).data) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithUnion), "::", stringify!(data)), - ); -} -impl Clone for WithUnion { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct RealAbstractionWithTonsOfMethods { - pub _address: u8, -} -#[test] -fn bindgen_test_layout_RealAbstractionWithTonsOfMethods() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(RealAbstractionWithTonsOfMethods)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(RealAbstractionWithTonsOfMethods)), - ); -} -extern "C" { - #[link_name = "\u{1}_ZNK32RealAbstractionWithTonsOfMethods3barEv"] - pub fn RealAbstractionWithTonsOfMethods_bar( - this: *const RealAbstractionWithTonsOfMethods, - ); -} -extern "C" { - #[link_name = "\u{1}_ZN32RealAbstractionWithTonsOfMethods3barEv"] - pub fn RealAbstractionWithTonsOfMethods_bar1( - this: *mut RealAbstractionWithTonsOfMethods, - ); -} -extern "C" { - #[link_name = "\u{1}_ZN32RealAbstractionWithTonsOfMethods3barEi"] - pub fn RealAbstractionWithTonsOfMethods_bar2( - this: *mut RealAbstractionWithTonsOfMethods, - foo: ::std::os::raw::c_int, - ); -} -extern "C" { - #[link_name = "\u{1}_ZN32RealAbstractionWithTonsOfMethods3staEv"] - pub fn RealAbstractionWithTonsOfMethods_sta(); -} -impl Clone for RealAbstractionWithTonsOfMethods { - fn clone(&self) -> Self { - *self - } -} -impl RealAbstractionWithTonsOfMethods { - #[inline] - pub unsafe fn bar(&self) { - RealAbstractionWithTonsOfMethods_bar(self) - } - #[inline] - pub unsafe fn bar1(&mut self) { - RealAbstractionWithTonsOfMethods_bar1(self) - } - #[inline] - pub unsafe fn bar2(&mut self, foo: ::std::os::raw::c_int) { - RealAbstractionWithTonsOfMethods_bar2(self, foo) - } - #[inline] - pub unsafe fn sta() { - RealAbstractionWithTonsOfMethods_sta() - } -} diff --git a/bindgen-tests/tests/expectations/tests/class_nested.rs b/bindgen-tests/tests/expectations/tests/class_nested.rs index 38db451b8b..080f5968bc 100644 --- a/bindgen-tests/tests/expectations/tests/class_nested.rs +++ b/bindgen-tests/tests/expectations/tests/class_nested.rs @@ -9,31 +9,17 @@ pub struct A { pub struct A_B { pub member_b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_A_B() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(A_B)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A_B)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member_b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A_B), "::", stringify!(member_b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A_B"][::std::mem::size_of::() - 4usize]; + ["Alignment of A_B"][::std::mem::align_of::() - 4usize]; + ["Offset of field: A_B::member_b"][::std::mem::offset_of!(A_B, member_b) - 0usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct A_D { - pub foo: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub foo: T, } impl Default for A_D { fn default() -> Self { @@ -44,70 +30,36 @@ impl Default for A_D { } } } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member_a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(member_a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 4usize]; + ["Alignment of A"][::std::mem::align_of::() - 4usize]; + ["Offset of field: A::member_a"][::std::mem::offset_of!(A, member_a) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct A_C { pub baz: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_A_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(A_C)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A_C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A_C), "::", stringify!(baz)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A_C"][::std::mem::size_of::() - 4usize]; + ["Alignment of A_C"][::std::mem::align_of::() - 4usize]; + ["Offset of field: A_C::baz"][::std::mem::offset_of!(A_C, baz) - 0usize]; +}; +unsafe extern "C" { pub static mut var: A_B; } -#[test] -fn __bindgen_test_layout_A_D_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(A_D < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(A_D < ::std::os::raw::c_int >), - ), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: A_D_open0_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: A_D_open0_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; +unsafe extern "C" { pub static mut baz: A_D<::std::os::raw::c_int>; } #[repr(C)] @@ -115,33 +67,23 @@ extern "C" { pub struct D { pub member: A_B, } -#[test] -fn bindgen_test_layout_D() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(D))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(D)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(D), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of D"][::std::mem::size_of::() - 4usize]; + ["Alignment of D"][::std::mem::align_of::() - 4usize]; + ["Offset of field: D::member"][::std::mem::offset_of!(D, member) - 0usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Templated { - pub member: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member: T, } #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Templated_Templated_inner { - pub member_ptr: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member_ptr: *mut T, } impl Default for Templated_Templated_inner { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/class_no_members.rs b/bindgen-tests/tests/expectations/tests/class_no_members.rs index d8c67ca52d..c50da6a02d 100644 --- a/bindgen-tests/tests/expectations/tests/class_no_members.rs +++ b/bindgen-tests/tests/expectations/tests/class_no_members.rs @@ -4,64 +4,35 @@ pub struct whatever { pub _address: u8, } -#[test] -fn bindgen_test_layout_whatever() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(whatever)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(whatever)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of whatever"][::std::mem::size_of::() - 1usize]; + ["Alignment of whatever"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct whatever_child { pub _address: u8, } -#[test] -fn bindgen_test_layout_whatever_child() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(whatever_child)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(whatever_child)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of whatever_child"][::std::mem::size_of::() - 1usize]; + ["Alignment of whatever_child"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct whatever_child_with_member { pub m_member: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_whatever_child_with_member() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(whatever_child_with_member)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(whatever_child_with_member)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m_member) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(whatever_child_with_member), - "::", - stringify!(m_member), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of whatever_child_with_member", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of whatever_child_with_member", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: whatever_child_with_member::m_member", + ][::std::mem::offset_of!(whatever_child_with_member, m_member) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/class_static.rs b/bindgen-tests/tests/expectations/tests/class_static.rs index f6f8a3b175..d448165d62 100644 --- a/bindgen-tests/tests/expectations/tests/class_static.rs +++ b/bindgen-tests/tests/expectations/tests/class_static.rs @@ -4,28 +4,20 @@ pub struct MyClass { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN7MyClass7exampleE"] pub static mut MyClass_example: *const ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN7MyClass26example_check_no_collisionE"] pub static mut MyClass_example_check_no_collision: *const ::std::os::raw::c_int; } -#[test] -fn bindgen_test_layout_MyClass() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(MyClass)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(MyClass)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of MyClass"][::std::mem::size_of::() - 1usize]; + ["Alignment of MyClass"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZL26example_check_no_collision"] pub static mut example_check_no_collision: *const ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/class_static_const.rs b/bindgen-tests/tests/expectations/tests/class_static_const.rs index c2cd5b3e9f..d628239c4c 100644 --- a/bindgen-tests/tests/expectations/tests/class_static_const.rs +++ b/bindgen-tests/tests/expectations/tests/class_static_const.rs @@ -7,12 +7,8 @@ pub struct A { pub const A_a: ::std::os::raw::c_int = 0; pub const A_b: i32 = 63; pub const A_c: u32 = 255; -#[test] -fn bindgen_test_layout_A() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(A)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 1usize]; + ["Alignment of A"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/class_use_as.rs b/bindgen-tests/tests/expectations/tests/class_use_as.rs index f01e8acb1b..ec898ff7eb 100644 --- a/bindgen-tests/tests/expectations/tests/class_use_as.rs +++ b/bindgen-tests/tests/expectations/tests/class_use_as.rs @@ -5,48 +5,22 @@ pub struct whatever { pub replacement: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_whatever() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(whatever)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(whatever)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).replacement) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(whatever), "::", stringify!(replacement)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of whatever"][::std::mem::size_of::() - 4usize]; + ["Alignment of whatever"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: whatever::replacement", + ][::std::mem::offset_of!(whatever, replacement) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct container { pub c: whatever, } -#[test] -fn bindgen_test_layout_container() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(container)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(container)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(container), "::", stringify!(c)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of container"][::std::mem::size_of::() - 4usize]; + ["Alignment of container"][::std::mem::align_of::() - 4usize]; + ["Offset of field: container::c"][::std::mem::offset_of!(container, c) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/class_with_dtor.rs b/bindgen-tests/tests/expectations/tests/class_with_dtor.rs index 75585e6351..aa99f42468 100644 --- a/bindgen-tests/tests/expectations/tests/class_with_dtor.rs +++ b/bindgen-tests/tests/expectations/tests/class_with_dtor.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct HandleWithDtor { - pub ptr: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub ptr: *mut T, } impl Default for HandleWithDtor { fn default() -> Self { @@ -20,31 +20,14 @@ pub type HandleValue = HandleWithDtor<::std::os::raw::c_int>; pub struct WithoutDtor { pub shouldBeWithDtor: HandleValue, } -#[test] -fn bindgen_test_layout_WithoutDtor() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(WithoutDtor)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(WithoutDtor)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).shouldBeWithDtor) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithoutDtor), - "::", - stringify!(shouldBeWithDtor), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithoutDtor"][::std::mem::size_of::() - 8usize]; + ["Alignment of WithoutDtor"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: WithoutDtor::shouldBeWithDtor", + ][::std::mem::offset_of!(WithoutDtor, shouldBeWithDtor) - 0usize]; +}; impl Default for WithoutDtor { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -54,22 +37,12 @@ impl Default for WithoutDtor { } } } -#[test] -fn __bindgen_test_layout_HandleWithDtor_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(HandleWithDtor < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(HandleWithDtor < ::std::os::raw::c_int >), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: HandleWithDtor_open0_int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: HandleWithDtor_open0_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/class_with_enum.rs b/bindgen-tests/tests/expectations/tests/class_with_enum.rs new file mode 100644 index 0000000000..ca1806357c --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/class_with_enum.rs @@ -0,0 +1,14 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone)] +pub struct A { + pub _address: u8, +} +pub const A_B_B1: A_B = 0; +pub const A_B_B2: A_B = 1; +pub type A_B = ::std::os::raw::c_uint; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 1usize]; + ["Alignment of A"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/class_with_inner_struct.rs b/bindgen-tests/tests/expectations/tests/class_with_inner_struct.rs index 1b0f511230..710026c72f 100644 --- a/bindgen-tests/tests/expectations/tests/class_with_inner_struct.rs +++ b/bindgen-tests/tests/expectations/tests/class_with_inner_struct.rs @@ -12,56 +12,28 @@ pub struct A_Segment { pub begin: ::std::os::raw::c_int, pub end: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_A_Segment() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(A_Segment)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A_Segment)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).begin) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A_Segment), "::", stringify!(begin)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).end) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(A_Segment), "::", stringify!(end)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A_Segment"][::std::mem::size_of::() - 8usize]; + ["Alignment of A_Segment"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: A_Segment::begin", + ][::std::mem::offset_of!(A_Segment, begin) - 0usize]; + ["Offset of field: A_Segment::end"][::std::mem::offset_of!(A_Segment, end) - 4usize]; +}; #[repr(C)] #[derive(Copy, Clone)] pub union A__bindgen_ty_1 { pub f: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_A__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(A__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A__bindgen_ty_1), "::", stringify!(f)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + ["Alignment of A__bindgen_ty_1"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: A__bindgen_ty_1::f", + ][::std::mem::offset_of!(A__bindgen_ty_1, f) - 0usize]; +}; impl Default for A__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -76,26 +48,14 @@ impl Default for A__bindgen_ty_1 { pub union A__bindgen_ty_2 { pub d: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_A__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(A__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A__bindgen_ty_2), "::", stringify!(d)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A__bindgen_ty_2"][::std::mem::size_of::() - 4usize]; + ["Alignment of A__bindgen_ty_2"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: A__bindgen_ty_2::d", + ][::std::mem::offset_of!(A__bindgen_ty_2, d) - 0usize]; +}; impl Default for A__bindgen_ty_2 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -105,27 +65,13 @@ impl Default for A__bindgen_ty_2 { } } } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 12usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(c)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).named_union) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(named_union)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 12usize]; + ["Alignment of A"][::std::mem::align_of::() - 4usize]; + ["Offset of field: A::c"][::std::mem::offset_of!(A, c) - 0usize]; + ["Offset of field: A::named_union"][::std::mem::offset_of!(A, named_union) - 4usize]; +}; impl Default for A { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -146,47 +92,21 @@ pub struct B_Segment { pub begin: ::std::os::raw::c_int, pub end: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_B_Segment() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(B_Segment)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(B_Segment)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).begin) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(B_Segment), "::", stringify!(begin)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).end) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(B_Segment), "::", stringify!(end)), - ); -} -#[test] -fn bindgen_test_layout_B() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(B)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(B), "::", stringify!(d)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of B_Segment"][::std::mem::size_of::() - 8usize]; + ["Alignment of B_Segment"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: B_Segment::begin", + ][::std::mem::offset_of!(B_Segment, begin) - 0usize]; + ["Offset of field: B_Segment::end"][::std::mem::offset_of!(B_Segment, end) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of B"][::std::mem::size_of::() - 4usize]; + ["Alignment of B"][::std::mem::align_of::() - 4usize]; + ["Offset of field: B::d"][::std::mem::offset_of!(B, d) - 0usize]; +}; #[repr(i32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum StepSyntax { @@ -215,102 +135,48 @@ pub struct C__bindgen_ty_1__bindgen_ty_1 { pub mX2: f32, pub mY2: f32, } -#[test] -fn bindgen_test_layout_C__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(C__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mX1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(mX1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mY1) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(mY1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mX2) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(mX2), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mY2) as usize - ptr as usize }, - 12usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(mY2), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of C__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of C__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: C__bindgen_ty_1__bindgen_ty_1::mX1", + ][::std::mem::offset_of!(C__bindgen_ty_1__bindgen_ty_1, mX1) - 0usize]; + [ + "Offset of field: C__bindgen_ty_1__bindgen_ty_1::mY1", + ][::std::mem::offset_of!(C__bindgen_ty_1__bindgen_ty_1, mY1) - 4usize]; + [ + "Offset of field: C__bindgen_ty_1__bindgen_ty_1::mX2", + ][::std::mem::offset_of!(C__bindgen_ty_1__bindgen_ty_1, mX2) - 8usize]; + [ + "Offset of field: C__bindgen_ty_1__bindgen_ty_1::mY2", + ][::std::mem::offset_of!(C__bindgen_ty_1__bindgen_ty_1, mY2) - 12usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct C__bindgen_ty_1__bindgen_ty_2 { pub mStepSyntax: StepSyntax, pub mSteps: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_C__bindgen_ty_1__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(C__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mStepSyntax) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(mStepSyntax), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mSteps) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(mSteps), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of C__bindgen_ty_1__bindgen_ty_2", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of C__bindgen_ty_1__bindgen_ty_2", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: C__bindgen_ty_1__bindgen_ty_2::mStepSyntax", + ][::std::mem::offset_of!(C__bindgen_ty_1__bindgen_ty_2, mStepSyntax) - 0usize]; + [ + "Offset of field: C__bindgen_ty_1__bindgen_ty_2::mSteps", + ][::std::mem::offset_of!(C__bindgen_ty_1__bindgen_ty_2, mSteps) - 4usize]; +}; impl Default for C__bindgen_ty_1__bindgen_ty_2 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -320,31 +186,14 @@ impl Default for C__bindgen_ty_1__bindgen_ty_2 { } } } -#[test] -fn bindgen_test_layout_C__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(C__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFunc) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1), - "::", - stringify!(mFunc), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C__bindgen_ty_1"][::std::mem::size_of::() - 16usize]; + ["Alignment of C__bindgen_ty_1"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: C__bindgen_ty_1::mFunc", + ][::std::mem::offset_of!(C__bindgen_ty_1, mFunc) - 0usize]; +}; impl Default for C__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -360,47 +209,21 @@ pub struct C_Segment { pub begin: ::std::os::raw::c_int, pub end: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_C_Segment() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(C_Segment)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C_Segment)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).begin) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C_Segment), "::", stringify!(begin)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).end) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(C_Segment), "::", stringify!(end)), - ); -} -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 20usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(d)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C_Segment"][::std::mem::size_of::() - 8usize]; + ["Alignment of C_Segment"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: C_Segment::begin", + ][::std::mem::offset_of!(C_Segment, begin) - 0usize]; + ["Offset of field: C_Segment::end"][::std::mem::offset_of!(C_Segment, end) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 20usize]; + ["Alignment of C"][::std::mem::align_of::() - 4usize]; + ["Offset of field: C::d"][::std::mem::offset_of!(C, d) - 0usize]; +}; impl Default for C { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/class_with_inner_struct_1_0.rs b/bindgen-tests/tests/expectations/tests/class_with_inner_struct_1_0.rs deleted file mode 100644 index b36faa6cf1..0000000000 --- a/bindgen-tests/tests/expectations/tests/class_with_inner_struct_1_0.rs +++ /dev/null @@ -1,468 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct A { - pub c: ::std::os::raw::c_uint, - pub named_union: A__bindgen_ty_1, - pub __bindgen_anon_1: A__bindgen_ty_2, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct A_Segment { - pub begin: ::std::os::raw::c_int, - pub end: ::std::os::raw::c_int, -} -#[test] -fn bindgen_test_layout_A_Segment() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(A_Segment)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A_Segment)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).begin) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A_Segment), "::", stringify!(begin)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).end) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(A_Segment), "::", stringify!(end)), - ); -} -impl Clone for A_Segment { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct A__bindgen_ty_1 { - pub f: __BindgenUnionField<::std::os::raw::c_int>, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_A__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(A__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A__bindgen_ty_1), "::", stringify!(f)), - ); -} -impl Clone for A__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct A__bindgen_ty_2 { - pub d: __BindgenUnionField<::std::os::raw::c_int>, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_A__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(A__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A__bindgen_ty_2), "::", stringify!(d)), - ); -} -impl Clone for A__bindgen_ty_2 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 12usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(c)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).named_union) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(named_union)), - ); -} -impl Clone for A { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct B { - pub d: ::std::os::raw::c_uint, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct B_Segment { - pub begin: ::std::os::raw::c_int, - pub end: ::std::os::raw::c_int, -} -#[test] -fn bindgen_test_layout_B_Segment() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(B_Segment)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(B_Segment)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).begin) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(B_Segment), "::", stringify!(begin)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).end) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(B_Segment), "::", stringify!(end)), - ); -} -impl Clone for B_Segment { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_B() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(B)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(B), "::", stringify!(d)), - ); -} -impl Clone for B { - fn clone(&self) -> Self { - *self - } -} -#[repr(i32)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum StepSyntax { - Keyword = 0, - FunctionalWithoutKeyword = 1, - FunctionalWithStartKeyword = 2, - FunctionalWithEndKeyword = 3, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq)] -pub struct C { - pub d: ::std::os::raw::c_uint, - pub __bindgen_anon_1: C__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq)] -pub struct C__bindgen_ty_1 { - pub mFunc: __BindgenUnionField, - pub __bindgen_anon_1: __BindgenUnionField, - pub bindgen_union_field: [u32; 4usize], -} -#[repr(C)] -#[derive(Debug, Default, Copy, PartialEq)] -pub struct C__bindgen_ty_1__bindgen_ty_1 { - pub mX1: f32, - pub mY1: f32, - pub mX2: f32, - pub mY2: f32, -} -#[test] -fn bindgen_test_layout_C__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(C__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mX1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(mX1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mY1) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(mY1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mX2) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(mX2), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mY2) as usize - ptr as usize }, - 12usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(mY2), - ), - ); -} -impl Clone for C__bindgen_ty_1__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct C__bindgen_ty_1__bindgen_ty_2 { - pub mStepSyntax: StepSyntax, - pub mSteps: ::std::os::raw::c_uint, -} -#[test] -fn bindgen_test_layout_C__bindgen_ty_1__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(C__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mStepSyntax) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(mStepSyntax), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mSteps) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(mSteps), - ), - ); -} -impl Clone for C__bindgen_ty_1__bindgen_ty_2 { - fn clone(&self) -> Self { - *self - } -} -impl Default for C__bindgen_ty_1__bindgen_ty_2 { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[test] -fn bindgen_test_layout_C__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(C__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFunc) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(C__bindgen_ty_1), - "::", - stringify!(mFunc), - ), - ); -} -impl Clone for C__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct C_Segment { - pub begin: ::std::os::raw::c_int, - pub end: ::std::os::raw::c_int, -} -#[test] -fn bindgen_test_layout_C_Segment() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(C_Segment)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C_Segment)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).begin) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C_Segment), "::", stringify!(begin)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).end) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(C_Segment), "::", stringify!(end)), - ); -} -impl Clone for C_Segment { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 20usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(d)), - ); -} -impl Clone for C { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/class_with_typedef.rs b/bindgen-tests/tests/expectations/tests/class_with_typedef.rs index ca9ea56ec4..73f2b55cc3 100644 --- a/bindgen-tests/tests/expectations/tests/class_with_typedef.rs +++ b/bindgen-tests/tests/expectations/tests/class_with_typedef.rs @@ -11,55 +11,29 @@ pub struct C { } pub type C_MyInt = ::std::os::raw::c_int; pub type C_Lookup = *const ::std::os::raw::c_char; -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 72usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(c)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ptr) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(ptr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arr) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(arr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 56usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(d)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).other_ptr) as usize - ptr as usize }, - 64usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(other_ptr)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 72usize]; + ["Alignment of C"][::std::mem::align_of::() - 8usize]; + ["Offset of field: C::c"][::std::mem::offset_of!(C, c) - 0usize]; + ["Offset of field: C::ptr"][::std::mem::offset_of!(C, ptr) - 8usize]; + ["Offset of field: C::arr"][::std::mem::offset_of!(C, arr) - 16usize]; + ["Offset of field: C::d"][::std::mem::offset_of!(C, d) - 56usize]; + ["Offset of field: C::other_ptr"][::std::mem::offset_of!(C, other_ptr) - 64usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN1C6methodEi"] pub fn C_method(this: *mut C, c: C_MyInt); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1C9methodRefERi"] pub fn C_methodRef(this: *mut C, c: *mut C_MyInt); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1C16complexMethodRefERPKc"] pub fn C_complexMethodRef(this: *mut C, c: *mut C_Lookup); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1C13anotherMethodEi"] pub fn C_anotherMethod(this: *mut C, c: AnotherInt); } @@ -96,22 +70,12 @@ pub struct D { pub _base: C, pub ptr: *mut C_MyInt, } -#[test] -fn bindgen_test_layout_D() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 80usize, concat!("Size of: ", stringify!(D))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(D)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ptr) as usize - ptr as usize }, - 72usize, - concat!("Offset of field: ", stringify!(D), "::", stringify!(ptr)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of D"][::std::mem::size_of::() - 80usize]; + ["Alignment of D"][::std::mem::align_of::() - 8usize]; + ["Offset of field: D::ptr"][::std::mem::offset_of!(D, ptr) - 72usize]; +}; impl Default for D { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/comment-indent.rs b/bindgen-tests/tests/expectations/tests/comment-indent.rs index 95fe892768..72b167d00c 100644 --- a/bindgen-tests/tests/expectations/tests/comment-indent.rs +++ b/bindgen-tests/tests/expectations/tests/comment-indent.rs @@ -19,32 +19,16 @@ pub mod root { pub struct Foo_Bar { pub _address: u8, } - #[test] - fn bindgen_test_layout_Foo_Bar() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo_Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo_Bar)), - ); - } - #[test] - fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Foo_Bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo_Bar"][::std::mem::align_of::() - 1usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; + }; pub mod test { #[allow(unused_imports)] use self::super::super::root; @@ -62,26 +46,14 @@ pub mod root { +------+ +-------+*/ pub member: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_Baz() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Baz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Baz), "::", stringify!(member)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Baz"][::std::mem::size_of::() - 4usize]; + ["Alignment of Baz"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: Baz::member", + ][::std::mem::offset_of!(Baz, member) - 0usize]; + }; /** I'm in an inline namespace, and as such I shouldn't get generated inside a rust module, except when the relevant option is specified. Also, this comment shouldn't be misaligned.*/ @@ -90,36 +62,20 @@ pub mod root { pub struct InInlineNS { pub _address: u8, } - #[test] - fn bindgen_test_layout_InInlineNS() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(InInlineNS)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(InInlineNS)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of InInlineNS"][::std::mem::size_of::() - 1usize]; + ["Alignment of InInlineNS"][::std::mem::align_of::() - 1usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Bazz { pub _address: u8, } - #[test] - fn bindgen_test_layout_Bazz() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Bazz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Bazz)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Bazz"][::std::mem::size_of::() - 1usize]; + ["Alignment of Bazz"][::std::mem::align_of::() - 1usize]; + }; } } diff --git a/bindgen-tests/tests/expectations/tests/complex.rs b/bindgen-tests/tests/expectations/tests/complex.rs index 7bcc1b9e04..233b86ea36 100644 --- a/bindgen-tests/tests/expectations/tests/complex.rs +++ b/bindgen-tests/tests/expectations/tests/complex.rs @@ -10,56 +10,27 @@ pub struct __BindgenComplex { pub struct TestDouble { pub mMember: __BindgenComplex, } -#[test] -fn bindgen_test_layout_TestDouble() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(TestDouble)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(TestDouble)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mMember) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(TestDouble), "::", stringify!(mMember)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TestDouble"][::std::mem::size_of::() - 16usize]; + ["Alignment of TestDouble"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: TestDouble::mMember", + ][::std::mem::offset_of!(TestDouble, mMember) - 0usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct TestDoublePtr { pub mMember: *mut __BindgenComplex, } -#[test] -fn bindgen_test_layout_TestDoublePtr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(TestDoublePtr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(TestDoublePtr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mMember) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(TestDoublePtr), - "::", - stringify!(mMember), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TestDoublePtr"][::std::mem::size_of::() - 8usize]; + ["Alignment of TestDoublePtr"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: TestDoublePtr::mMember", + ][::std::mem::offset_of!(TestDoublePtr, mMember) - 0usize]; +}; impl Default for TestDoublePtr { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -74,51 +45,27 @@ impl Default for TestDoublePtr { pub struct TestFloat { pub mMember: __BindgenComplex, } -#[test] -fn bindgen_test_layout_TestFloat() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(TestFloat)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(TestFloat)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mMember) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(TestFloat), "::", stringify!(mMember)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TestFloat"][::std::mem::size_of::() - 8usize]; + ["Alignment of TestFloat"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: TestFloat::mMember", + ][::std::mem::offset_of!(TestFloat, mMember) - 0usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct TestFloatPtr { pub mMember: *mut __BindgenComplex, } -#[test] -fn bindgen_test_layout_TestFloatPtr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(TestFloatPtr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(TestFloatPtr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mMember) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(TestFloatPtr), "::", stringify!(mMember)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TestFloatPtr"][::std::mem::size_of::() - 8usize]; + ["Alignment of TestFloatPtr"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: TestFloatPtr::mMember", + ][::std::mem::offset_of!(TestFloatPtr, mMember) - 0usize]; +}; impl Default for TestFloatPtr { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/complex_global.rs b/bindgen-tests/tests/expectations/tests/complex_global.rs index 101ad0f49f..c818df676e 100644 --- a/bindgen-tests/tests/expectations/tests/complex_global.rs +++ b/bindgen-tests/tests/expectations/tests/complex_global.rs @@ -5,12 +5,12 @@ pub struct __BindgenComplex { pub re: T, pub im: T, } -extern "C" { +unsafe extern "C" { pub static mut globalValueFloat: __BindgenComplex; } -extern "C" { +unsafe extern "C" { pub static mut globalValueDouble: __BindgenComplex; } -extern "C" { +unsafe extern "C" { pub static mut globalValueLongDouble: __BindgenComplex; } diff --git a/bindgen-tests/tests/expectations/tests/const-const-mut-ptr.rs b/bindgen-tests/tests/expectations/tests/const-const-mut-ptr.rs index e165b8de9b..72a34da105 100644 --- a/bindgen-tests/tests/expectations/tests/const-const-mut-ptr.rs +++ b/bindgen-tests/tests/expectations/tests/const-const-mut-ptr.rs @@ -4,26 +4,12 @@ pub struct foo { pub bar: *const *const *mut *const ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/const_array.rs b/bindgen-tests/tests/expectations/tests/const_array.rs index 8dae42d116..30852deb36 100644 --- a/bindgen-tests/tests/expectations/tests/const_array.rs +++ b/bindgen-tests/tests/expectations/tests/const_array.rs @@ -1,7 +1,7 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub static foo: [::std::os::raw::c_int; 1usize]; } -extern "C" { +unsafe extern "C" { pub static mut bar: [::std::os::raw::c_int; 1usize]; } diff --git a/bindgen-tests/tests/expectations/tests/const_array_fn_arg.rs b/bindgen-tests/tests/expectations/tests/const_array_fn_arg.rs index 035a56fa78..fb26311115 100644 --- a/bindgen-tests/tests/expectations/tests/const_array_fn_arg.rs +++ b/bindgen-tests/tests/expectations/tests/const_array_fn_arg.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn f(a: *const ::std::os::raw::c_int); } diff --git a/bindgen-tests/tests/expectations/tests/const_array_typedef.rs b/bindgen-tests/tests/expectations/tests/const_array_typedef.rs new file mode 100644 index 0000000000..034856d359 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/const_array_typedef.rs @@ -0,0 +1,28 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone)] +pub struct strct { + pub field: ::std::os::raw::c_int, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of strct"][::std::mem::size_of::() - 4usize]; + ["Alignment of strct"][::std::mem::align_of::() - 4usize]; + ["Offset of field: strct::field"][::std::mem::offset_of!(strct, field) - 0usize]; +}; +pub type typ = [strct; 1usize]; +unsafe extern "C" { + pub static mut w: typ; +} +unsafe extern "C" { + pub static mut x: *mut strct; +} +unsafe extern "C" { + pub static y: typ; +} +unsafe extern "C" { + pub static mut z: *const strct; +} +unsafe extern "C" { + pub fn function(a: *const strct, b: *const strct); +} diff --git a/bindgen-tests/tests/expectations/tests/const_bool.rs b/bindgen-tests/tests/expectations/tests/const_bool.rs index 97cb7ec691..2cbab47390 100644 --- a/bindgen-tests/tests/expectations/tests/const_bool.rs +++ b/bindgen-tests/tests/expectations/tests/const_bool.rs @@ -6,14 +6,10 @@ pub struct A { pub _address: u8, } pub const A_k: bool = false; -#[test] -fn bindgen_test_layout_A() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(A)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 1usize]; + ["Alignment of A"][::std::mem::align_of::() - 1usize]; +}; pub type foo = bool; pub const k2: foo = true; diff --git a/bindgen-tests/tests/expectations/tests/const_enum_unnamed.rs b/bindgen-tests/tests/expectations/tests/const_enum_unnamed.rs index 3648a48e28..f49d825224 100644 --- a/bindgen-tests/tests/expectations/tests/const_enum_unnamed.rs +++ b/bindgen-tests/tests/expectations/tests/const_enum_unnamed.rs @@ -18,16 +18,8 @@ pub const Foo_FOO_BAR: Foo__bindgen_ty_1 = Foo__bindgen_ty_1::FOO_BAR; pub enum Foo__bindgen_ty_1 { FOO_BAR = 10, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/const_multidim_array_fn_arg.rs b/bindgen-tests/tests/expectations/tests/const_multidim_array_fn_arg.rs index 0c4670b0ed..db0ce114fb 100644 --- a/bindgen-tests/tests/expectations/tests/const_multidim_array_fn_arg.rs +++ b/bindgen-tests/tests/expectations/tests/const_multidim_array_fn_arg.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn f(a: *const [::std::os::raw::c_int; 1usize]); } diff --git a/bindgen-tests/tests/expectations/tests/const_ptr.rs b/bindgen-tests/tests/expectations/tests/const_ptr.rs index c08aa73d7e..9b9e38c1e7 100644 --- a/bindgen-tests/tests/expectations/tests/const_ptr.rs +++ b/bindgen-tests/tests/expectations/tests/const_ptr.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(bar: *const ::std::os::raw::c_void); } diff --git a/bindgen-tests/tests/expectations/tests/const_resolved_ty.rs b/bindgen-tests/tests/expectations/tests/const_resolved_ty.rs index 20a124b474..ed49b69f64 100644 --- a/bindgen-tests/tests/expectations/tests/const_resolved_ty.rs +++ b/bindgen-tests/tests/expectations/tests/const_resolved_ty.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(foo: *const u8); } diff --git a/bindgen-tests/tests/expectations/tests/const_tparam.rs b/bindgen-tests/tests/expectations/tests/const_tparam.rs index 12c0c2e509..c6b16a8959 100644 --- a/bindgen-tests/tests/expectations/tests/const_tparam.rs +++ b/bindgen-tests/tests/expectations/tests/const_tparam.rs @@ -2,9 +2,9 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct C { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub foo: *const T, pub bar: *const T, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for C { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/constified-enum-module-overflow.rs b/bindgen-tests/tests/expectations/tests/constified-enum-module-overflow.rs index 61e666d2a0..e5eada9abc 100644 --- a/bindgen-tests/tests/expectations/tests/constified-enum-module-overflow.rs +++ b/bindgen-tests/tests/expectations/tests/constified-enum-module-overflow.rs @@ -15,45 +15,27 @@ pub type C_U = B; pub struct A { pub u: B, } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(u)), - ); -} -#[test] -fn __bindgen_test_layout_C_open0_A_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(C)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(C)), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_A_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(B)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(B)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 1usize]; + ["Alignment of A"][::std::mem::align_of::() - 1usize]; + ["Offset of field: A::u"][::std::mem::offset_of!(A, u) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: C_open0_A_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: C_open0_A_close0", + ][::std::mem::align_of::() - 1usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_A_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: B_open0_A_close0", + ][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/constify-all-enums.rs b/bindgen-tests/tests/expectations/tests/constify-all-enums.rs index de5d949283..7913454b56 100644 --- a/bindgen-tests/tests/expectations/tests/constify-all-enums.rs +++ b/bindgen-tests/tests/expectations/tests/constify-all-enums.rs @@ -8,26 +8,14 @@ pub type foo = ::std::os::raw::c_uint; pub struct bar { pub this_should_work: foo, } -#[test] -fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).this_should_work) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(this_should_work)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of bar"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: bar::this_should_work", + ][::std::mem::offset_of!(bar, this_should_work) - 0usize]; +}; impl Default for bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/constify-module-enums-basic.rs b/bindgen-tests/tests/expectations/tests/constify-module-enums-basic.rs index 7f0ea58101..f7d0f1baa6 100644 --- a/bindgen-tests/tests/expectations/tests/constify-module-enums-basic.rs +++ b/bindgen-tests/tests/expectations/tests/constify-module-enums-basic.rs @@ -12,26 +12,14 @@ pub use self::foo_alias1 as foo_alias2; pub struct bar { pub this_should_work: foo::Type, } -#[test] -fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).this_should_work) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(this_should_work)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of bar"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: bar::this_should_work", + ][::std::mem::offset_of!(bar, this_should_work) - 0usize]; +}; impl Default for bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -41,14 +29,14 @@ impl Default for bar { } } } -extern "C" { +unsafe extern "C" { pub fn func1( arg1: foo::Type, arg2: *mut foo::Type, arg3: *mut *mut foo::Type, ) -> *mut foo::Type; } -extern "C" { +unsafe extern "C" { pub fn func2( arg1: foo_alias1, arg2: *mut foo_alias1, diff --git a/bindgen-tests/tests/expectations/tests/constify-module-enums-namespace.rs b/bindgen-tests/tests/expectations/tests/constify-module-enums-namespace.rs index d8faac4fa3..883478a824 100644 --- a/bindgen-tests/tests/expectations/tests/constify-module-enums-namespace.rs +++ b/bindgen-tests/tests/expectations/tests/constify-module-enums-namespace.rs @@ -24,34 +24,14 @@ pub mod root { pub struct bar { pub this_should_work: root::ns1::ns2::foo::Type, } - #[test] - fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).this_should_work) as usize - - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(bar), - "::", - stringify!(this_should_work), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of bar"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: bar::this_should_work", + ][::std::mem::offset_of!(bar, this_should_work) - 0usize]; + }; impl Default for bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/constify-module-enums-shadow-name.rs b/bindgen-tests/tests/expectations/tests/constify-module-enums-shadow-name.rs index 4780df6841..b5e4243c94 100644 --- a/bindgen-tests/tests/expectations/tests/constify-module-enums-shadow-name.rs +++ b/bindgen-tests/tests/expectations/tests/constify-module-enums-shadow-name.rs @@ -11,26 +11,12 @@ pub mod foo { pub struct bar { pub member: foo::Type, } -#[test] -fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: bar::member"][::std::mem::offset_of!(bar, member) - 0usize]; +}; impl Default for bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/constify-module-enums-simple-alias.rs b/bindgen-tests/tests/expectations/tests/constify-module-enums-simple-alias.rs index 791f2b3054..63d48ef795 100644 --- a/bindgen-tests/tests/expectations/tests/constify-module-enums-simple-alias.rs +++ b/bindgen-tests/tests/expectations/tests/constify-module-enums-simple-alias.rs @@ -20,61 +20,19 @@ pub struct Bar { pub baz_ptr3: *mut Foo_alias2, pub baz_ptr4: *mut Foo_alias3, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 48usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz1) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz2) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz3) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz3)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz4) as usize - ptr as usize }, - 12usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz4)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz_ptr1) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz_ptr1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz_ptr2) as usize - ptr as usize }, - 24usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz_ptr2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz_ptr3) as usize - ptr as usize }, - 32usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz_ptr3)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz_ptr4) as usize - ptr as usize }, - 40usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz_ptr4)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 48usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::baz1"][::std::mem::offset_of!(Bar, baz1) - 0usize]; + ["Offset of field: Bar::baz2"][::std::mem::offset_of!(Bar, baz2) - 4usize]; + ["Offset of field: Bar::baz3"][::std::mem::offset_of!(Bar, baz3) - 8usize]; + ["Offset of field: Bar::baz4"][::std::mem::offset_of!(Bar, baz4) - 12usize]; + ["Offset of field: Bar::baz_ptr1"][::std::mem::offset_of!(Bar, baz_ptr1) - 16usize]; + ["Offset of field: Bar::baz_ptr2"][::std::mem::offset_of!(Bar, baz_ptr2) - 24usize]; + ["Offset of field: Bar::baz_ptr3"][::std::mem::offset_of!(Bar, baz_ptr3) - 32usize]; + ["Offset of field: Bar::baz_ptr4"][::std::mem::offset_of!(Bar, baz_ptr4) - 40usize]; +}; impl Default for Bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/constify-module-enums-simple-nonamespace.rs b/bindgen-tests/tests/expectations/tests/constify-module-enums-simple-nonamespace.rs index 363768a0d0..80fa0734da 100644 --- a/bindgen-tests/tests/expectations/tests/constify-module-enums-simple-nonamespace.rs +++ b/bindgen-tests/tests/expectations/tests/constify-module-enums-simple-nonamespace.rs @@ -10,31 +10,13 @@ pub struct Bar { pub baz1: one_Foo::Type, pub baz2: *mut one_Foo::Type, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz1) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz2) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz2)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 16usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::baz1"][::std::mem::offset_of!(Bar, baz1) - 0usize]; + ["Offset of field: Bar::baz2"][::std::mem::offset_of!(Bar, baz2) - 8usize]; +}; impl Default for Bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/constify-module-enums-types.rs b/bindgen-tests/tests/expectations/tests/constify-module-enums-types.rs index 687deb45c1..6ba94cb3b9 100644 --- a/bindgen-tests/tests/expectations/tests/constify-module-enums-types.rs +++ b/bindgen-tests/tests/expectations/tests/constify-module-enums-types.rs @@ -45,71 +45,21 @@ pub struct bar { pub member9: anon_enum_alias2, pub member10: anon_enum_alias3, } -#[test] -fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 48usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member1) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member2) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member3) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member3)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member4) as usize - ptr as usize }, - 12usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member4)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member5) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member5)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member6) as usize - ptr as usize }, - 24usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member6)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member7) as usize - ptr as usize }, - 32usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member7)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member8) as usize - ptr as usize }, - 36usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member8)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member9) as usize - ptr as usize }, - 40usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member9)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member10) as usize - ptr as usize }, - 44usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(member10)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar"][::std::mem::size_of::() - 48usize]; + ["Alignment of bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: bar::member1"][::std::mem::offset_of!(bar, member1) - 0usize]; + ["Offset of field: bar::member2"][::std::mem::offset_of!(bar, member2) - 4usize]; + ["Offset of field: bar::member3"][::std::mem::offset_of!(bar, member3) - 8usize]; + ["Offset of field: bar::member4"][::std::mem::offset_of!(bar, member4) - 12usize]; + ["Offset of field: bar::member5"][::std::mem::offset_of!(bar, member5) - 16usize]; + ["Offset of field: bar::member6"][::std::mem::offset_of!(bar, member6) - 24usize]; + ["Offset of field: bar::member7"][::std::mem::offset_of!(bar, member7) - 32usize]; + ["Offset of field: bar::member8"][::std::mem::offset_of!(bar, member8) - 36usize]; + ["Offset of field: bar::member9"][::std::mem::offset_of!(bar, member9) - 40usize]; + ["Offset of field: bar::member10"][::std::mem::offset_of!(bar, member10) - 44usize]; +}; impl Default for bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -124,26 +74,12 @@ impl Default for bar { pub struct Baz { pub member1: ns2_Foo::Type, } -#[test] -fn bindgen_test_layout_Baz() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Baz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member1) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Baz), "::", stringify!(member1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Baz"][::std::mem::size_of::() - 4usize]; + ["Alignment of Baz"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Baz::member1"][::std::mem::offset_of!(Baz, member1) - 0usize]; +}; impl Default for Baz { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -163,26 +99,12 @@ pub mod one_Foo { pub struct Bar { pub baz: *mut one_Foo::Type, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::baz"][::std::mem::offset_of!(Bar, baz) - 0usize]; +}; impl Default for Bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -192,7 +114,7 @@ impl Default for Bar { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z5func13fooPS_PS0_"] pub fn func1( arg1: foo::Type, @@ -200,7 +122,7 @@ extern "C" { arg3: *mut *mut foo::Type, ) -> *mut foo::Type; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z5func23fooPS_PS0_"] pub fn func2( arg1: foo_alias1, @@ -211,8 +133,8 @@ extern "C" { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Thing { - pub thing: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub thing: T, } impl Default for Thing { fn default() -> Self { @@ -223,11 +145,11 @@ impl Default for Thing { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z5func35ThingI3fooE"] pub fn func3(arg1: Thing) -> foo::Type; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z5func45ThingIS_I3fooEE"] pub fn func4(arg1: Thing>) -> foo::Type; } diff --git a/bindgen-tests/tests/expectations/tests/constructor-tp.rs b/bindgen-tests/tests/expectations/tests/constructor-tp.rs index 5f3be0b4d9..2585311d29 100644 --- a/bindgen-tests/tests/expectations/tests/constructor-tp.rs +++ b/bindgen-tests/tests/expectations/tests/constructor-tp.rs @@ -9,20 +9,12 @@ pub struct Foo { pub struct Bar { pub _address: u8, } -#[test] -fn bindgen_test_layout_Bar() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Bar)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3BarC1Ev"] pub fn Bar_Bar(this: *mut Bar); } diff --git a/bindgen-tests/tests/expectations/tests/constructors.rs b/bindgen-tests/tests/expectations/tests/constructors.rs index 75c05d3050..45c29e61e5 100644 --- a/bindgen-tests/tests/expectations/tests/constructors.rs +++ b/bindgen-tests/tests/expectations/tests/constructors.rs @@ -4,27 +4,19 @@ pub struct TestOverload { pub _address: u8, } -#[test] -fn bindgen_test_layout_TestOverload() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(TestOverload)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(TestOverload)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TestOverload"][::std::mem::size_of::() - 1usize]; + ["Alignment of TestOverload"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN12TestOverloadC1Ei"] pub fn TestOverload_TestOverload( this: *mut TestOverload, arg1: ::std::os::raw::c_int, ); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN12TestOverloadC1Ed"] pub fn TestOverload_TestOverload1(this: *mut TestOverload, arg1: f64); } @@ -47,20 +39,14 @@ impl TestOverload { pub struct TestPublicNoArgs { pub _address: u8, } -#[test] -fn bindgen_test_layout_TestPublicNoArgs() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(TestPublicNoArgs)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(TestPublicNoArgs)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TestPublicNoArgs"][::std::mem::size_of::() - 1usize]; + [ + "Alignment of TestPublicNoArgs", + ][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN16TestPublicNoArgsC1Ev"] pub fn TestPublicNoArgs_TestPublicNoArgs(this: *mut TestPublicNoArgs); } diff --git a/bindgen-tests/tests/expectations/tests/constructors_1_33.rs b/bindgen-tests/tests/expectations/tests/constructors_1_33.rs index 5d523e848e..0563b4e65d 100644 --- a/bindgen-tests/tests/expectations/tests/constructors_1_33.rs +++ b/bindgen-tests/tests/expectations/tests/constructors_1_33.rs @@ -6,15 +6,11 @@ pub struct TestOverload { } #[test] fn bindgen_test_layout_TestOverload() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(TestOverload)), - ); + assert_eq!(::std::mem::size_of::(), 1usize, "Size of TestOverload"); assert_eq!( ::std::mem::align_of::(), 1usize, - concat!("Alignment of ", stringify!(TestOverload)), + "Alignment of TestOverload", ); } extern "C" { @@ -54,12 +50,12 @@ fn bindgen_test_layout_TestPublicNoArgs() { assert_eq!( ::std::mem::size_of::(), 1usize, - concat!("Size of: ", stringify!(TestPublicNoArgs)), + "Size of TestPublicNoArgs", ); assert_eq!( ::std::mem::align_of::(), 1usize, - concat!("Alignment of ", stringify!(TestPublicNoArgs)), + "Alignment of TestPublicNoArgs", ); } extern "C" { diff --git a/bindgen-tests/tests/expectations/tests/contains-vs-inherits-zero-sized.rs b/bindgen-tests/tests/expectations/tests/contains-vs-inherits-zero-sized.rs index 70a4180757..3362280843 100644 --- a/bindgen-tests/tests/expectations/tests/contains-vs-inherits-zero-sized.rs +++ b/bindgen-tests/tests/expectations/tests/contains-vs-inherits-zero-sized.rs @@ -5,19 +5,11 @@ pub struct Empty { pub _address: u8, } -#[test] -fn bindgen_test_layout_Empty() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Empty)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Empty)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Empty"][::std::mem::size_of::() - 1usize]; + ["Alignment of Empty"][::std::mem::align_of::() - 1usize]; +}; /** This should not get an `_address` byte, so `sizeof(Inherits)` should be `1`.*/ #[repr(C)] @@ -25,26 +17,12 @@ fn bindgen_test_layout_Empty() { pub struct Inherits { pub b: bool, } -#[test] -fn bindgen_test_layout_Inherits() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Inherits)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Inherits)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Inherits), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Inherits"][::std::mem::size_of::() - 1usize]; + ["Alignment of Inherits"][::std::mem::align_of::() - 1usize]; + ["Offset of field: Inherits::b"][::std::mem::offset_of!(Inherits, b) - 0usize]; +}; /** This should not get an `_address` byte, but contains `Empty` which *does* get one, so `sizeof(Contains)` should be `1 + 1`.*/ #[repr(C)] @@ -53,28 +31,12 @@ pub struct Contains { pub empty: Empty, pub b: bool, } -#[test] -fn bindgen_test_layout_Contains() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(Contains)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Contains)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).empty) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Contains), "::", stringify!(empty)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 1usize, - concat!("Offset of field: ", stringify!(Contains), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Contains"][::std::mem::size_of::() - 2usize]; + ["Alignment of Contains"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: Contains::empty", + ][::std::mem::offset_of!(Contains, empty) - 0usize]; + ["Offset of field: Contains::b"][::std::mem::offset_of!(Contains, b) - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/convert-floats.rs b/bindgen-tests/tests/expectations/tests/convert-floats.rs index 3f45f76f5d..9ca939f7c5 100644 --- a/bindgen-tests/tests/expectations/tests/convert-floats.rs +++ b/bindgen-tests/tests/expectations/tests/convert-floats.rs @@ -15,51 +15,21 @@ pub struct foo { pub complexFloat: __BindgenComplex<::std::os::raw::c_float>, pub complexDouble: __BindgenComplex<::std::os::raw::c_double>, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 48usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(baz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bazz) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bazz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bazzz) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bazzz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).complexFloat) as usize - ptr as usize }, - 24usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(complexFloat)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).complexDouble) as usize - ptr as usize }, - 32usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(complexDouble)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 48usize]; + ["Alignment of foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; + ["Offset of field: foo::baz"][::std::mem::offset_of!(foo, baz) - 4usize]; + ["Offset of field: foo::bazz"][::std::mem::offset_of!(foo, bazz) - 8usize]; + ["Offset of field: foo::bazzz"][::std::mem::offset_of!(foo, bazzz) - 16usize]; + [ + "Offset of field: foo::complexFloat", + ][::std::mem::offset_of!(foo, complexFloat) - 24usize]; + [ + "Offset of field: foo::complexDouble", + ][::std::mem::offset_of!(foo, complexDouble) - 32usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/cpp-empty-layout.rs b/bindgen-tests/tests/expectations/tests/cpp-empty-layout.rs index d51ccfa80c..551dff82cf 100644 --- a/bindgen-tests/tests/expectations/tests/cpp-empty-layout.rs +++ b/bindgen-tests/tests/expectations/tests/cpp-empty-layout.rs @@ -4,16 +4,8 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/crtp.rs b/bindgen-tests/tests/expectations/tests/crtp.rs index 6a953d7704..68397041b7 100644 --- a/bindgen-tests/tests/expectations/tests/crtp.rs +++ b/bindgen-tests/tests/expectations/tests/crtp.rs @@ -9,19 +9,11 @@ pub struct Base { pub struct Derived { pub _address: u8, } -#[test] -fn bindgen_test_layout_Derived() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Derived)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Derived)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Derived"][::std::mem::size_of::() - 1usize]; + ["Alignment of Derived"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default)] pub struct BaseWithDestructor { @@ -32,42 +24,30 @@ pub struct BaseWithDestructor { pub struct DerivedFromBaseWithDestructor { pub _address: u8, } -#[test] -fn bindgen_test_layout_DerivedFromBaseWithDestructor() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(DerivedFromBaseWithDestructor)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(DerivedFromBaseWithDestructor)), - ); -} -#[test] -fn __bindgen_test_layout_Base_open0_Derived_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(Base)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(Base)), - ); -} -#[test] -fn __bindgen_test_layout_BaseWithDestructor_open0_DerivedFromBaseWithDestructor_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(BaseWithDestructor)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(BaseWithDestructor)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of DerivedFromBaseWithDestructor", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of DerivedFromBaseWithDestructor", + ][::std::mem::align_of::() - 1usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Base_open0_Derived_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: Base_open0_Derived_close0", + ][::std::mem::align_of::() - 1usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: BaseWithDestructor_open0_DerivedFromBaseWithDestructor_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: BaseWithDestructor_open0_DerivedFromBaseWithDestructor_close0", + ][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/ctypes-prefix-path.rs b/bindgen-tests/tests/expectations/tests/ctypes-prefix-path.rs index c2da364afa..5f947f9cea 100644 --- a/bindgen-tests/tests/expectations/tests/ctypes-prefix-path.rs +++ b/bindgen-tests/tests/expectations/tests/ctypes-prefix-path.rs @@ -13,36 +13,14 @@ pub struct foo { pub b: libc::foo::c_int, pub bar: *mut libc::foo::c_void, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::core::mem::MaybeUninit = ::core::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::core::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::core::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::core::mem::size_of::() - 16usize]; + ["Alignment of foo"][::core::mem::align_of::() - 8usize]; + ["Offset of field: foo::a"][::core::mem::offset_of!(foo, a) - 0usize]; + ["Offset of field: foo::b"][::core::mem::offset_of!(foo, b) - 4usize]; + ["Offset of field: foo::bar"][::core::mem::offset_of!(foo, bar) - 8usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::core::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/decl_extern_int_twice.rs b/bindgen-tests/tests/expectations/tests/decl_extern_int_twice.rs index 8be0ea58e9..122d41a12d 100644 --- a/bindgen-tests/tests/expectations/tests/decl_extern_int_twice.rs +++ b/bindgen-tests/tests/expectations/tests/decl_extern_int_twice.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub static mut foo: ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/decl_ptr_to_array.rs b/bindgen-tests/tests/expectations/tests/decl_ptr_to_array.rs index 08cf113a4c..a559d33b4a 100644 --- a/bindgen-tests/tests/expectations/tests/decl_ptr_to_array.rs +++ b/bindgen-tests/tests/expectations/tests/decl_ptr_to_array.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub static mut foo: *mut [::std::os::raw::c_int; 1usize]; } diff --git a/bindgen-tests/tests/expectations/tests/default-enum-style-constified-module.rs b/bindgen-tests/tests/expectations/tests/default-enum-style-constified-module.rs index c9897de70b..60c84e47df 100644 --- a/bindgen-tests/tests/expectations/tests/default-enum-style-constified-module.rs +++ b/bindgen-tests/tests/expectations/tests/default-enum-style-constified-module.rs @@ -5,6 +5,6 @@ pub mod Foo { pub const baz: Type = 1; pub const blap: Type = 2; } -extern "C" { +unsafe extern "C" { pub fn func(x: Foo::Type); } diff --git a/bindgen-tests/tests/expectations/tests/default-macro-constant-type-signed.rs b/bindgen-tests/tests/expectations/tests/default-macro-constant-type-signed.rs index db4eaa99bd..7fca57b6b9 100644 --- a/bindgen-tests/tests/expectations/tests/default-macro-constant-type-signed.rs +++ b/bindgen-tests/tests/expectations/tests/default-macro-constant-type-signed.rs @@ -30,7 +30,7 @@ pub const MIN_U32_Minus1: i32 = -1; pub const MIN_I32_Minus1: i64 = -2147483649; pub const LONG12: i64 = 123456789012; pub const LONG_12: i64 = -123456789012; -extern "C" { +unsafe extern "C" { pub fn foo( arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, @@ -40,7 +40,7 @@ extern "C" { arg6: ::std::os::raw::c_schar, ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { pub fn bar( arg1: ::std::os::raw::c_long, arg2: ::std::os::raw::c_longlong, diff --git a/bindgen-tests/tests/expectations/tests/default-macro-constant-type-unsigned.rs b/bindgen-tests/tests/expectations/tests/default-macro-constant-type-unsigned.rs index bc122e981f..d34d050a1a 100644 --- a/bindgen-tests/tests/expectations/tests/default-macro-constant-type-unsigned.rs +++ b/bindgen-tests/tests/expectations/tests/default-macro-constant-type-unsigned.rs @@ -30,7 +30,7 @@ pub const MIN_U32_Minus1: i32 = -1; pub const MIN_I32_Minus1: i64 = -2147483649; pub const LONG12: u64 = 123456789012; pub const LONG_12: i64 = -123456789012; -extern "C" { +unsafe extern "C" { pub fn foo( arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, @@ -40,7 +40,7 @@ extern "C" { arg6: ::std::os::raw::c_schar, ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { pub fn bar( arg1: ::std::os::raw::c_long, arg2: ::std::os::raw::c_longlong, diff --git a/bindgen-tests/tests/expectations/tests/default-macro-constant-type.rs b/bindgen-tests/tests/expectations/tests/default-macro-constant-type.rs index bc122e981f..d34d050a1a 100644 --- a/bindgen-tests/tests/expectations/tests/default-macro-constant-type.rs +++ b/bindgen-tests/tests/expectations/tests/default-macro-constant-type.rs @@ -30,7 +30,7 @@ pub const MIN_U32_Minus1: i32 = -1; pub const MIN_I32_Minus1: i64 = -2147483649; pub const LONG12: u64 = 123456789012; pub const LONG_12: i64 = -123456789012; -extern "C" { +unsafe extern "C" { pub fn foo( arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, @@ -40,7 +40,7 @@ extern "C" { arg6: ::std::os::raw::c_schar, ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { pub fn bar( arg1: ::std::os::raw::c_long, arg2: ::std::os::raw::c_longlong, diff --git a/bindgen-tests/tests/expectations/tests/default-template-parameter.rs b/bindgen-tests/tests/expectations/tests/default-template-parameter.rs index dc279e3d90..67f8a486de 100644 --- a/bindgen-tests/tests/expectations/tests/default-template-parameter.rs +++ b/bindgen-tests/tests/expectations/tests/default-template-parameter.rs @@ -2,10 +2,10 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Foo { - pub t: T, - pub u: U, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, + pub u: U, } impl Default for Foo { fn default() -> Self { @@ -16,26 +16,16 @@ impl Default for Foo { } } } -#[test] -fn __bindgen_test_layout_Foo_open0_bool__int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(Foo < bool, ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(Foo < bool, ::std::os::raw::c_int >), - ), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Foo_open0_bool__int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: Foo_open0_bool__int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZL3bar"] pub static mut bar: Foo; } diff --git a/bindgen-tests/tests/expectations/tests/default_visibility_crate.rs b/bindgen-tests/tests/expectations/tests/default_visibility_crate.rs index aef1a61a08..aeb6a717f6 100644 --- a/bindgen-tests/tests/expectations/tests/default_visibility_crate.rs +++ b/bindgen-tests/tests/expectations/tests/default_visibility_crate.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -108,6 +170,30 @@ impl Color { } } #[inline] + pub(crate) unsafe fn r_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + pub(crate) unsafe fn set_r_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub(crate) fn g(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u8) } } @@ -119,6 +205,30 @@ impl Color { } } #[inline] + pub(crate) unsafe fn g_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) as u8, + ) + } + } + #[inline] + pub(crate) unsafe fn set_g_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub(crate) fn b(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u8) } } @@ -130,6 +240,30 @@ impl Color { } } #[inline] + pub(crate) unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 1u8) as u8, + ) + } + } + #[inline] + pub(crate) unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub(crate) fn new_bitfield_1( r: ::std::os::raw::c_char, g: ::std::os::raw::c_char, diff --git a/bindgen-tests/tests/expectations/tests/default_visibility_private.rs b/bindgen-tests/tests/expectations/tests/default_visibility_private.rs index 8b3099c0d8..4ee26721b0 100644 --- a/bindgen-tests/tests/expectations/tests/default_visibility_private.rs +++ b/bindgen-tests/tests/expectations/tests/default_visibility_private.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -108,6 +170,30 @@ impl Color { } } #[inline] + unsafe fn r_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + unsafe fn set_r_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] fn g(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u8) } } @@ -119,6 +205,30 @@ impl Color { } } #[inline] + unsafe fn g_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) as u8, + ) + } + } + #[inline] + unsafe fn set_g_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] fn b(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u8) } } @@ -130,6 +240,30 @@ impl Color { } } #[inline] + unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 1u8) as u8, + ) + } + } + #[inline] + unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] fn new_bitfield_1( r: ::std::os::raw::c_char, g: ::std::os::raw::c_char, diff --git a/bindgen-tests/tests/expectations/tests/default_visibility_private_respects_cxx_access_spec.rs b/bindgen-tests/tests/expectations/tests/default_visibility_private_respects_cxx_access_spec.rs index 29fbb3a893..e676f6470d 100644 --- a/bindgen-tests/tests/expectations/tests/default_visibility_private_respects_cxx_access_spec.rs +++ b/bindgen-tests/tests/expectations/tests/default_visibility_private_respects_cxx_access_spec.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -108,6 +170,30 @@ impl Color { } } #[inline] + pub unsafe fn r_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_r_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn g(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u8) } } @@ -119,6 +205,30 @@ impl Color { } } #[inline] + pub unsafe fn g_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_g_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b(&self) -> ::std::os::raw::c_char { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u8) } } @@ -130,6 +240,30 @@ impl Color { } } #[inline] + pub unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] fn new_bitfield_1( r: ::std::os::raw::c_char, g: ::std::os::raw::c_char, diff --git a/bindgen-tests/tests/expectations/tests/deleted-function.rs b/bindgen-tests/tests/expectations/tests/deleted-function.rs index 3d29bd872c..fc8588121f 100644 --- a/bindgen-tests/tests/expectations/tests/deleted-function.rs +++ b/bindgen-tests/tests/expectations/tests/deleted-function.rs @@ -4,20 +4,16 @@ pub struct A { pub _address: u8, } -#[test] -fn bindgen_test_layout_A() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(A)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 1usize]; + ["Alignment of A"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN1A17inline_definitionEv"] pub fn A_inline_definition(this: *mut A); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1A22out_of_line_definitionEv"] pub fn A_out_of_line_definition(this: *mut A); } @@ -36,30 +32,22 @@ impl A { pub struct B { pub _address: u8, } -#[test] -fn bindgen_test_layout_B() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(B)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of B"][::std::mem::size_of::() - 1usize]; + ["Alignment of B"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct C { pub _address: u8, } -#[test] -fn bindgen_test_layout_C() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(C)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 1usize]; + ["Alignment of C"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN1CC1ERS_"] pub fn C_C(this: *mut C, arg1: *mut C); } diff --git a/bindgen-tests/tests/expectations/tests/derive-bitfield-method-same-name.rs b/bindgen-tests/tests/expectations/tests/derive-bitfield-method-same-name.rs index e3236f58fe..05e66a72bc 100644 --- a/bindgen-tests/tests/expectations/tests/derive-bitfield-method-same-name.rs +++ b/bindgen-tests/tests/expectations/tests/derive-bitfield-method-same-name.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,28 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -98,20 +102,12 @@ pub struct Foo { fn bindgen_test_layout_Foo() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 136usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); + assert_eq!(::std::mem::size_of::(), 136usize, "Size of Foo"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of Foo"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).large) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(large)), + "Offset of field: Foo::large", ); } extern "C" { @@ -140,12 +136,18 @@ impl ::std::fmt::Debug for Foo { write!( f, "Foo {{ large: [{}], type_ : {:?}, }}", - self - .large - .iter() - .enumerate() - .map(|(i, v)| format!("{}{:?}", if i > 0 { ", " } else { "" }, v)) - .collect::(), + { + use std::fmt::Write as _; + let mut output = String::new(); + let mut iter = self.large.iter(); + if let Some(value) = iter.next() { + let _ = write!(output, "{value:?}"); + for value in iter { + let _ = write!(output, ", {value:?}"); + } + } + output + }, self.type__bindgen_bitfield(), ) } diff --git a/bindgen-tests/tests/expectations/tests/derive-clone.rs b/bindgen-tests/tests/expectations/tests/derive-clone.rs index b11287453c..d903afa06f 100644 --- a/bindgen-tests/tests/expectations/tests/derive-clone.rs +++ b/bindgen-tests/tests/expectations/tests/derive-clone.rs @@ -12,22 +12,17 @@ fn bindgen_test_layout_ShouldDeriveClone() { assert_eq!( ::std::mem::size_of::(), 132usize, - concat!("Size of: ", stringify!(ShouldDeriveClone)), + "Size of ShouldDeriveClone", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(ShouldDeriveClone)), + "Alignment of ShouldDeriveClone", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).large) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldDeriveClone), - "::", - stringify!(large), - ), + "Offset of field: ShouldDeriveClone::large", ); } impl Default for ShouldDeriveClone { diff --git a/bindgen-tests/tests/expectations/tests/derive-clone_1_0.rs b/bindgen-tests/tests/expectations/tests/derive-clone_1_0.rs deleted file mode 100644 index 2702c94793..0000000000 --- a/bindgen-tests/tests/expectations/tests/derive-clone_1_0.rs +++ /dev/null @@ -1,47 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -/** Since builtin `Clone` impls were introduced in Rust 1.21 this struct - should impl `Clone` "manually".*/ -#[repr(C)] -#[derive(Copy)] -pub struct ShouldImplClone { - pub large: [::std::os::raw::c_int; 33usize], -} -#[test] -fn bindgen_test_layout_ShouldImplClone() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 132usize, - concat!("Size of: ", stringify!(ShouldImplClone)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ShouldImplClone)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).large) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldImplClone), - "::", - stringify!(large), - ), - ); -} -impl Clone for ShouldImplClone { - fn clone(&self) -> Self { - *self - } -} -impl Default for ShouldImplClone { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} diff --git a/bindgen-tests/tests/expectations/tests/derive-custom-cli.rs b/bindgen-tests/tests/expectations/tests/derive-custom-cli.rs index 5784684556..59a3a76571 100644 --- a/bindgen-tests/tests/expectations/tests/derive-custom-cli.rs +++ b/bindgen-tests/tests/expectations/tests/derive-custom-cli.rs @@ -4,26 +4,14 @@ pub struct foo_struct { pub inner: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_foo_struct() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo_struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo_struct)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).inner) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo_struct), "::", stringify!(inner)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo_struct"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo_struct"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo_struct::inner", + ][::std::mem::offset_of!(foo_struct, inner) - 0usize]; +}; #[repr(u32)] #[derive(Clone, Hash, PartialEq, Eq, Copy)] pub enum foo_enum { @@ -35,52 +23,22 @@ pub union foo_union { pub fst: ::std::mem::ManuallyDrop<::std::os::raw::c_int>, pub snd: ::std::mem::ManuallyDrop, } -#[test] -fn bindgen_test_layout_foo_union() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo_union)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo_union)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).fst) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo_union), "::", stringify!(fst)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).snd) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo_union), "::", stringify!(snd)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo_union"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo_union"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo_union::fst"][::std::mem::offset_of!(foo_union, fst) - 0usize]; + ["Offset of field: foo_union::snd"][::std::mem::offset_of!(foo_union, snd) - 0usize]; +}; #[repr(C)] pub struct non_matching { pub inner: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_non_matching() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(non_matching)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(non_matching)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).inner) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(non_matching), "::", stringify!(inner)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of non_matching"][::std::mem::size_of::() - 4usize]; + ["Alignment of non_matching"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: non_matching::inner", + ][::std::mem::offset_of!(non_matching, inner) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/derive-debug-bitfield-1-51.rs b/bindgen-tests/tests/expectations/tests/derive-debug-bitfield-1-51.rs new file mode 100644 index 0000000000..351d3b31e5 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/derive-debug-bitfield-1-51.rs @@ -0,0 +1,270 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct __BindgenBitfieldUnit { + storage: Storage, +} +impl __BindgenBitfieldUnit { + #[inline] + pub const fn new(storage: Storage) -> Self { + Self { storage } + } +} +impl __BindgenBitfieldUnit +where + Storage: AsRef<[u8]> + AsMut<[u8]>, +{ + #[inline] + fn extract_bit(byte: u8, index: usize) -> bool { + let bit_index = if cfg!(target_endian = "big") { + 7 - (index % 8) + } else { + index % 8 + }; + let mask = 1 << bit_index; + byte & mask == mask + } + #[inline] + pub fn get_bit(&self, index: usize) -> bool { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { + let bit_index = if cfg!(target_endian = "big") { + 7 - (index % 8) + } else { + index % 8 + }; + let mask = 1 << bit_index; + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; + } + #[inline] + pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if self.get_bit(i + bit_offset) { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] + pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + self.set_bit(index + bit_offset, val_bit_is_set); + } + } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct C { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, + pub large_array: [::std::os::raw::c_int; 50usize], +} +#[test] +fn bindgen_test_layout_C() { + const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); + let ptr = UNINIT.as_ptr(); + assert_eq!(::std::mem::size_of::(), 204usize, "Size of C"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of C"); + assert_eq!( + unsafe { ::std::ptr::addr_of!((*ptr).large_array) as usize - ptr as usize }, + 4usize, + "Offset of field: C::large_array", + ); +} +impl Default for C { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl C { + #[inline] + pub fn a(&self) -> bool { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u8) } + } + #[inline] + pub fn set_a(&mut self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn a_raw(this: *const Self) -> bool { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn b(&self) -> bool { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 7u8) as u8) } + } + #[inline] + pub fn set_b(&mut self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 7u8, val as u64) + } + } + #[inline] + pub unsafe fn b_raw(this: *const Self) -> bool { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 7u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 7u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(a: bool, b: bool) -> __BindgenBitfieldUnit<[u8; 1usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); + __bindgen_bitfield_unit + .set( + 0usize, + 1u8, + { + let a: u8 = unsafe { ::std::mem::transmute(a) }; + a as u64 + }, + ); + __bindgen_bitfield_unit + .set( + 1usize, + 7u8, + { + let b: u8 = unsafe { ::std::mem::transmute(b) }; + b as u64 + }, + ); + __bindgen_bitfield_unit + } +} diff --git a/bindgen-tests/tests/expectations/tests/derive-debug-bitfield-core.rs b/bindgen-tests/tests/expectations/tests/derive-debug-bitfield-core.rs index 54b44b33d2..edcb4e2a02 100644 --- a/bindgen-tests/tests/expectations/tests/derive-debug-bitfield-core.rs +++ b/bindgen-tests/tests/expectations/tests/derive-debug-bitfield-core.rs @@ -16,10 +16,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -29,21 +26,28 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -95,20 +99,12 @@ pub struct C { fn bindgen_test_layout_C() { const UNINIT: ::core::mem::MaybeUninit = ::core::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::core::mem::size_of::(), - 204usize, - concat!("Size of: ", stringify!(C)), - ); - assert_eq!( - ::core::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); + assert_eq!(::core::mem::size_of::(), 204usize, "Size of C"); + assert_eq!(::core::mem::align_of::(), 4usize, "Alignment of C"); assert_eq!( unsafe { ::core::ptr::addr_of!((*ptr).large_array) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(large_array)), + "Offset of field: C::large_array", ); } impl Default for C { diff --git a/bindgen-tests/tests/expectations/tests/derive-debug-bitfield.rs b/bindgen-tests/tests/expectations/tests/derive-debug-bitfield.rs index 828383af4e..e266880509 100644 --- a/bindgen-tests/tests/expectations/tests/derive-debug-bitfield.rs +++ b/bindgen-tests/tests/expectations/tests/derive-debug-bitfield.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,28 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -94,20 +98,12 @@ pub struct C { fn bindgen_test_layout_C() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 204usize, - concat!("Size of: ", stringify!(C)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); + assert_eq!(::std::mem::size_of::(), 204usize, "Size of C"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of C"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).large_array) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(large_array)), + "Offset of field: C::large_array", ); } impl Default for C { @@ -126,12 +122,18 @@ impl ::std::fmt::Debug for C { "C {{ a : {:?}, b : {:?}, large_array: [{}] }}", self.a(), self.b(), - self - .large_array - .iter() - .enumerate() - .map(|(i, v)| format!("{}{:?}", if i > 0 { ", " } else { "" }, v)) - .collect::(), + { + use std::fmt::Write as _; + let mut output = String::new(); + let mut iter = self.large_array.iter(); + if let Some(value) = iter.next() { + let _ = write!(output, "{value:?}"); + for value in iter { + let _ = write!(output, ", {value:?}"); + } + } + output + }, ) } } diff --git a/bindgen-tests/tests/expectations/tests/derive-debug-function-pointer.rs b/bindgen-tests/tests/expectations/tests/derive-debug-function-pointer.rs index 2ca5a839ed..9fe1f5518c 100644 --- a/bindgen-tests/tests/expectations/tests/derive-debug-function-pointer.rs +++ b/bindgen-tests/tests/expectations/tests/derive-debug-function-pointer.rs @@ -12,25 +12,17 @@ pub type Nice_Function = ::std::option::Option< fn bindgen_test_layout_Nice() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 144usize, - concat!("Size of: ", stringify!(Nice)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Nice)), - ); + assert_eq!(::std::mem::size_of::(), 144usize, "Size of Nice"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of Nice"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pointer) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Nice), "::", stringify!(pointer)), + "Offset of field: Nice::pointer", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).large_array) as usize - ptr as usize }, 8usize, - concat!("Offset of field: ", stringify!(Nice), "::", stringify!(large_array)), + "Offset of field: Nice::large_array", ); } impl Default for Nice { @@ -48,12 +40,18 @@ impl ::std::fmt::Debug for Nice { f, "Nice {{ pointer: {:?}, large_array: [{}] }}", self.pointer, - self - .large_array - .iter() - .enumerate() - .map(|(i, v)| format!("{}{:?}", if i > 0 { ", " } else { "" }, v)) - .collect::(), + { + use std::fmt::Write as _; + let mut output = String::new(); + let mut iter = self.large_array.iter(); + if let Some(value) = iter.next() { + let _ = write!(output, "{value:?}"); + for value in iter { + let _ = write!(output, ", {value:?}"); + } + } + output + }, ) } } diff --git a/bindgen-tests/tests/expectations/tests/derive-debug-generic.rs b/bindgen-tests/tests/expectations/tests/derive-debug-generic.rs index f35b28b3e5..de6ce385ac 100644 --- a/bindgen-tests/tests/expectations/tests/derive-debug-generic.rs +++ b/bindgen-tests/tests/expectations/tests/derive-debug-generic.rs @@ -1,8 +1,8 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #[repr(C)] pub struct Generic { - pub t: [T; 40usize], pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: [T; 40usize], } impl Default for Generic { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/derive-debug-mangle-name.rs b/bindgen-tests/tests/expectations/tests/derive-debug-mangle-name.rs index b93a425af6..34b4a87d65 100644 --- a/bindgen-tests/tests/expectations/tests/derive-debug-mangle-name.rs +++ b/bindgen-tests/tests/expectations/tests/derive-debug-mangle-name.rs @@ -12,41 +12,21 @@ pub union perf_event_attr__bindgen_ty_1 { pub b: ::std::os::raw::c_int, pub c: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_perf_event_attr__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(perf_event_attr__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(perf_event_attr__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(perf_event_attr__bindgen_ty_1), - "::", - stringify!(b), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(perf_event_attr__bindgen_ty_1), - "::", - stringify!(c), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of perf_event_attr__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of perf_event_attr__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: perf_event_attr__bindgen_ty_1::b", + ][::std::mem::offset_of!(perf_event_attr__bindgen_ty_1, b) - 0usize]; + [ + "Offset of field: perf_event_attr__bindgen_ty_1::c", + ][::std::mem::offset_of!(perf_event_attr__bindgen_ty_1, c) - 0usize]; +}; impl Default for perf_event_attr__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -61,36 +41,17 @@ impl ::std::fmt::Debug for perf_event_attr__bindgen_ty_1 { write!(f, "perf_event_attr__bindgen_ty_1 {{ union }}") } } -#[test] -fn bindgen_test_layout_perf_event_attr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(perf_event_attr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(perf_event_attr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).type_) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(perf_event_attr), - "::", - stringify!(type_), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(perf_event_attr), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of perf_event_attr"][::std::mem::size_of::() - 12usize]; + ["Alignment of perf_event_attr"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: perf_event_attr::type_", + ][::std::mem::offset_of!(perf_event_attr, type_) - 0usize]; + [ + "Offset of field: perf_event_attr::a", + ][::std::mem::offset_of!(perf_event_attr, a) - 4usize]; +}; impl Default for perf_event_attr { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-debug-opaque-template-instantiation.rs b/bindgen-tests/tests/expectations/tests/derive-debug-opaque-template-instantiation.rs index 812bf0283f..d586278614 100644 --- a/bindgen-tests/tests/expectations/tests/derive-debug-opaque-template-instantiation.rs +++ b/bindgen-tests/tests/expectations/tests/derive-debug-opaque-template-instantiation.rs @@ -7,20 +7,12 @@ pub struct Instance { fn bindgen_test_layout_Instance() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 200usize, - concat!("Size of: ", stringify!(Instance)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Instance)), - ); + assert_eq!(::std::mem::size_of::(), 200usize, "Size of Instance"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of Instance"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).val) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Instance), "::", stringify!(val)), + "Offset of field: Instance::val", ); } impl Default for Instance { diff --git a/bindgen-tests/tests/expectations/tests/derive-debug-opaque.rs b/bindgen-tests/tests/expectations/tests/derive-debug-opaque.rs index b214562c0f..13ddfd5ada 100644 --- a/bindgen-tests/tests/expectations/tests/derive-debug-opaque.rs +++ b/bindgen-tests/tests/expectations/tests/derive-debug-opaque.rs @@ -6,16 +6,8 @@ pub struct Opaque { } #[test] fn bindgen_test_layout_Opaque() { - assert_eq!( - ::std::mem::size_of::(), - 164usize, - concat!("Size of: ", stringify!(Opaque)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Opaque)), - ); + assert_eq!(::std::mem::size_of::(), 164usize, "Size of Opaque"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of Opaque"); } impl Default for Opaque { fn default() -> Self { @@ -39,20 +31,12 @@ pub struct OpaqueUser { fn bindgen_test_layout_OpaqueUser() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 164usize, - concat!("Size of: ", stringify!(OpaqueUser)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(OpaqueUser)), - ); + assert_eq!(::std::mem::size_of::(), 164usize, "Size of OpaqueUser"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of OpaqueUser"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).opaque) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(OpaqueUser), "::", stringify!(opaque)), + "Offset of field: OpaqueUser::opaque", ); } impl Default for OpaqueUser { diff --git a/bindgen-tests/tests/expectations/tests/derive-default-and-blocklist.rs b/bindgen-tests/tests/expectations/tests/derive-default-and-blocklist.rs index 131df71c22..6ce99e5093 100644 --- a/bindgen-tests/tests/expectations/tests/derive-default-and-blocklist.rs +++ b/bindgen-tests/tests/expectations/tests/derive-default-and-blocklist.rs @@ -6,31 +6,18 @@ pub struct BlocklistMe(u8); pub struct ShouldNotDeriveDefault { pub a: BlocklistMe, } -#[test] -fn bindgen_test_layout_ShouldNotDeriveDefault() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ShouldNotDeriveDefault)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ShouldNotDeriveDefault)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldNotDeriveDefault), - "::", - stringify!(a), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ShouldNotDeriveDefault", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of ShouldNotDeriveDefault", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ShouldNotDeriveDefault::a", + ][::std::mem::offset_of!(ShouldNotDeriveDefault, a) - 0usize]; +}; impl Default for ShouldNotDeriveDefault { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-fn-ptr.rs b/bindgen-tests/tests/expectations/tests/derive-fn-ptr.rs index 395e31c5b5..f4b09474ae 100644 --- a/bindgen-tests/tests/expectations/tests/derive-fn-ptr.rs +++ b/bindgen-tests/tests/expectations/tests/derive-fn-ptr.rs @@ -24,26 +24,12 @@ pub type my_fun_t = ::std::option::Option< pub struct Foo { pub callback: my_fun_t, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).callback) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(callback)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Foo::callback"][::std::mem::offset_of!(Foo, callback) - 0usize]; +}; pub type my_fun2_t = ::std::option::Option< unsafe extern "C" fn( arg1: ::std::os::raw::c_int, @@ -65,23 +51,9 @@ pub type my_fun2_t = ::std::option::Option< pub struct Bar { pub callback: my_fun2_t, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).callback) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(callback)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::callback"][::std::mem::offset_of!(Bar, callback) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/derive-hash-and-blocklist.rs b/bindgen-tests/tests/expectations/tests/derive-hash-and-blocklist.rs index 98b3a11f85..c52047e8b8 100644 --- a/bindgen-tests/tests/expectations/tests/derive-hash-and-blocklist.rs +++ b/bindgen-tests/tests/expectations/tests/derive-hash-and-blocklist.rs @@ -5,31 +5,18 @@ pub struct BlocklistMe(u8); pub struct ShouldNotDeriveHash { pub a: BlocklistMe, } -#[test] -fn bindgen_test_layout_ShouldNotDeriveHash() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ShouldNotDeriveHash)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ShouldNotDeriveHash)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldNotDeriveHash), - "::", - stringify!(a), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ShouldNotDeriveHash", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of ShouldNotDeriveHash", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ShouldNotDeriveHash::a", + ][::std::mem::offset_of!(ShouldNotDeriveHash, a) - 0usize]; +}; impl Default for ShouldNotDeriveHash { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-hash-blocklisting.rs b/bindgen-tests/tests/expectations/tests/derive-hash-blocklisting.rs index dd6f3e26b7..e3223f08d7 100644 --- a/bindgen-tests/tests/expectations/tests/derive-hash-blocklisting.rs +++ b/bindgen-tests/tests/expectations/tests/derive-hash-blocklisting.rs @@ -11,26 +11,14 @@ pub struct Blocklisted { pub struct AllowlistedOne { pub a: Blocklisted<::std::os::raw::c_int>, } -#[test] -fn bindgen_test_layout_AllowlistedOne() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(AllowlistedOne)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(AllowlistedOne)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AllowlistedOne), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AllowlistedOne"][::std::mem::size_of::() - 4usize]; + ["Alignment of AllowlistedOne"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: AllowlistedOne::a", + ][::std::mem::offset_of!(AllowlistedOne, a) - 0usize]; +}; impl Default for AllowlistedOne { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -45,26 +33,14 @@ impl Default for AllowlistedOne { pub struct AllowlistedTwo { pub b: Blocklisted, } -#[test] -fn bindgen_test_layout_AllowlistedTwo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(AllowlistedTwo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(AllowlistedTwo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AllowlistedTwo), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AllowlistedTwo"][::std::mem::size_of::() - 4usize]; + ["Alignment of AllowlistedTwo"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: AllowlistedTwo::b", + ][::std::mem::offset_of!(AllowlistedTwo, b) - 0usize]; +}; impl Default for AllowlistedTwo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-anon-struct-float.rs b/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-anon-struct-float.rs index 25b2ad6b6f..2d66015fe7 100644 --- a/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-anon-struct-float.rs +++ b/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-anon-struct-float.rs @@ -11,48 +11,22 @@ pub struct foo__bindgen_ty_1 { pub a: f32, pub b: f32, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-float-array.rs b/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-float-array.rs index aa990eceb4..254a50b3e3 100644 --- a/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-float-array.rs +++ b/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-float-array.rs @@ -5,23 +5,9 @@ pub struct foo { pub bar: [f32; 3usize], } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 12usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-incomplete-array.rs b/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-incomplete-array.rs index d1b4c9004a..2588a49eed 100644 --- a/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-incomplete-array.rs +++ b/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-incomplete-array.rs @@ -35,74 +35,30 @@ pub struct test { pub a: ::std::os::raw::c_int, pub zero_length_array: __IncompleteArrayField<::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_test() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(test)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(test), "::", stringify!(a)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize - }, - 4usize, - concat!( - "Offset of field: ", - stringify!(test), - "::", - stringify!(zero_length_array), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of test"][::std::mem::size_of::() - 4usize]; + ["Alignment of test"][::std::mem::align_of::() - 4usize]; + ["Offset of field: test::a"][::std::mem::offset_of!(test, a) - 0usize]; + [ + "Offset of field: test::zero_length_array", + ][::std::mem::offset_of!(test, zero_length_array) - 4usize]; +}; #[repr(C)] #[derive(Debug, Default)] pub struct test2 { pub a: ::std::os::raw::c_int, pub incomplete_array: __IncompleteArrayField<::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_test2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(test2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(test2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(test2), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(test2), - "::", - stringify!(incomplete_array), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of test2"][::std::mem::size_of::() - 4usize]; + ["Alignment of test2"][::std::mem::align_of::() - 4usize]; + ["Offset of field: test2::a"][::std::mem::offset_of!(test2, a) - 0usize]; + [ + "Offset of field: test2::incomplete_array", + ][::std::mem::offset_of!(test2, incomplete_array) - 4usize]; +}; #[repr(C)] #[derive(Debug, Default)] pub struct test3 { @@ -110,45 +66,15 @@ pub struct test3 { pub zero_length_array: __IncompleteArrayField<::std::os::raw::c_char>, pub incomplete_array: __IncompleteArrayField<::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_test3() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(test3)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(test3)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(test3), "::", stringify!(a)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).zero_length_array) as usize - ptr as usize - }, - 4usize, - concat!( - "Offset of field: ", - stringify!(test3), - "::", - stringify!(zero_length_array), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).incomplete_array) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(test3), - "::", - stringify!(incomplete_array), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of test3"][::std::mem::size_of::() - 4usize]; + ["Alignment of test3"][::std::mem::align_of::() - 4usize]; + ["Offset of field: test3::a"][::std::mem::offset_of!(test3, a) - 0usize]; + [ + "Offset of field: test3::zero_length_array", + ][::std::mem::offset_of!(test3, zero_length_array) - 4usize]; + [ + "Offset of field: test3::incomplete_array", + ][::std::mem::offset_of!(test3, incomplete_array) - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-pointer.rs b/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-pointer.rs index 616a046f5e..5240d969db 100644 --- a/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-pointer.rs +++ b/bindgen-tests/tests/expectations/tests/derive-hash-struct-with-pointer.rs @@ -5,26 +5,14 @@ pub struct ConstPtrMutObj { pub bar: *mut ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_ConstPtrMutObj() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(ConstPtrMutObj)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ConstPtrMutObj)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(ConstPtrMutObj), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ConstPtrMutObj"][::std::mem::size_of::() - 8usize]; + ["Alignment of ConstPtrMutObj"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: ConstPtrMutObj::bar", + ][::std::mem::offset_of!(ConstPtrMutObj, bar) - 0usize]; +}; impl Default for ConstPtrMutObj { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -39,26 +27,14 @@ impl Default for ConstPtrMutObj { pub struct MutPtrMutObj { pub bar: *mut ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_MutPtrMutObj() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(MutPtrMutObj)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(MutPtrMutObj)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(MutPtrMutObj), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of MutPtrMutObj"][::std::mem::size_of::() - 8usize]; + ["Alignment of MutPtrMutObj"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: MutPtrMutObj::bar", + ][::std::mem::offset_of!(MutPtrMutObj, bar) - 0usize]; +}; impl Default for MutPtrMutObj { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -73,26 +49,14 @@ impl Default for MutPtrMutObj { pub struct MutPtrConstObj { pub bar: *const ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_MutPtrConstObj() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(MutPtrConstObj)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(MutPtrConstObj)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(MutPtrConstObj), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of MutPtrConstObj"][::std::mem::size_of::() - 8usize]; + ["Alignment of MutPtrConstObj"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: MutPtrConstObj::bar", + ][::std::mem::offset_of!(MutPtrConstObj, bar) - 0usize]; +}; impl Default for MutPtrConstObj { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -107,26 +71,16 @@ impl Default for MutPtrConstObj { pub struct ConstPtrConstObj { pub bar: *const ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_ConstPtrConstObj() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(ConstPtrConstObj)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ConstPtrConstObj)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(ConstPtrConstObj), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ConstPtrConstObj"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of ConstPtrConstObj", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: ConstPtrConstObj::bar", + ][::std::mem::offset_of!(ConstPtrConstObj, bar) - 0usize]; +}; impl Default for ConstPtrConstObj { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-hash-template-def-float.rs b/bindgen-tests/tests/expectations/tests/derive-hash-template-def-float.rs index cf251c4508..af09533cca 100644 --- a/bindgen-tests/tests/expectations/tests/derive-hash-template-def-float.rs +++ b/bindgen-tests/tests/expectations/tests/derive-hash-template-def-float.rs @@ -3,9 +3,9 @@ #[repr(C)] #[derive(Debug, Copy, Clone, PartialOrd, PartialEq)] pub struct foo { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub data: T, pub b: f32, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for foo { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/derive-hash-template-inst-float.rs b/bindgen-tests/tests/expectations/tests/derive-hash-template-inst-float.rs index 57a716fa58..10ed002e6e 100644 --- a/bindgen-tests/tests/expectations/tests/derive-hash-template-inst-float.rs +++ b/bindgen-tests/tests/expectations/tests/derive-hash-template-inst-float.rs @@ -3,8 +3,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct foo { - pub data: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub data: T, } impl Default for foo { fn default() -> Self { @@ -21,26 +21,12 @@ impl Default for foo { pub struct IntStr { pub a: foo<::std::os::raw::c_int>, } -#[test] -fn bindgen_test_layout_IntStr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(IntStr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(IntStr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(IntStr), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of IntStr"][::std::mem::size_of::() - 4usize]; + ["Alignment of IntStr"][::std::mem::align_of::() - 4usize]; + ["Offset of field: IntStr::a"][::std::mem::offset_of!(IntStr, a) - 0usize]; +}; impl Default for IntStr { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -56,26 +42,12 @@ impl Default for IntStr { pub struct FloatStr { pub a: foo, } -#[test] -fn bindgen_test_layout_FloatStr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(FloatStr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(FloatStr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(FloatStr), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of FloatStr"][::std::mem::size_of::() - 4usize]; + ["Alignment of FloatStr"][::std::mem::align_of::() - 4usize]; + ["Offset of field: FloatStr::a"][::std::mem::offset_of!(FloatStr, a) - 0usize]; +}; impl Default for FloatStr { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -85,35 +57,21 @@ impl Default for FloatStr { } } } -#[test] -fn __bindgen_test_layout_foo_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(foo < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(foo < ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_foo_open0_float_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!("Size of template specialization: ", stringify!(foo < f32 >)), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!("Alignment of template specialization: ", stringify!(foo < f32 >)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: foo_open0_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: foo_open0_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: foo_open0_float_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: foo_open0_float_close0", + ][::std::mem::align_of::>() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/derive-partialeq-and-blocklist.rs b/bindgen-tests/tests/expectations/tests/derive-partialeq-and-blocklist.rs index 614d0e674f..d24981061c 100644 --- a/bindgen-tests/tests/expectations/tests/derive-partialeq-and-blocklist.rs +++ b/bindgen-tests/tests/expectations/tests/derive-partialeq-and-blocklist.rs @@ -6,31 +6,18 @@ pub struct BlocklistMe(u8); pub struct ShouldNotDerivePartialEq { pub a: BlocklistMe, } -#[test] -fn bindgen_test_layout_ShouldNotDerivePartialEq() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ShouldNotDerivePartialEq)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ShouldNotDerivePartialEq)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldNotDerivePartialEq), - "::", - stringify!(a), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ShouldNotDerivePartialEq", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of ShouldNotDerivePartialEq", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ShouldNotDerivePartialEq::a", + ][::std::mem::offset_of!(ShouldNotDerivePartialEq, a) - 0usize]; +}; impl Default for ShouldNotDerivePartialEq { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-partialeq-anonfield.rs b/bindgen-tests/tests/expectations/tests/derive-partialeq-anonfield.rs index b7be202924..c4eb08df60 100644 --- a/bindgen-tests/tests/expectations/tests/derive-partialeq-anonfield.rs +++ b/bindgen-tests/tests/expectations/tests/derive-partialeq-anonfield.rs @@ -11,19 +11,15 @@ pub struct rte_mbuf { pub struct rte_mbuf__bindgen_ty_1 { pub bindgen_union_field: [u8; 0usize], } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_1", + ][::std::mem::size_of::() - 0usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_1", + ][::std::mem::align_of::() - 1usize]; +}; impl Default for rte_mbuf__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -33,19 +29,11 @@ impl Default for rte_mbuf__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_rte_mbuf() { - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(rte_mbuf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 64usize, - concat!("Alignment of ", stringify!(rte_mbuf)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_mbuf"][::std::mem::size_of::() - 0usize]; + ["Alignment of rte_mbuf"][::std::mem::align_of::() - 64usize]; +}; impl Default for rte_mbuf { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-partialeq-base.rs b/bindgen-tests/tests/expectations/tests/derive-partialeq-base.rs index 785bcbe0b1..d0768416ec 100644 --- a/bindgen-tests/tests/expectations/tests/derive-partialeq-base.rs +++ b/bindgen-tests/tests/expectations/tests/derive-partialeq-base.rs @@ -8,20 +8,12 @@ pub struct Base { fn bindgen_test_layout_Base() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 132usize, - concat!("Size of: ", stringify!(Base)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Base)), - ); + assert_eq!(::std::mem::size_of::(), 132usize, "Size of Base"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of Base"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).large) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Base), "::", stringify!(large)), + "Offset of field: Base::large", ); } impl Default for Base { @@ -48,12 +40,12 @@ fn bindgen_test_layout_ShouldDerivePartialEq() { assert_eq!( ::std::mem::size_of::(), 132usize, - concat!("Size of: ", stringify!(ShouldDerivePartialEq)), + "Size of ShouldDerivePartialEq", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(ShouldDerivePartialEq)), + "Alignment of ShouldDerivePartialEq", ); } impl Default for ShouldDerivePartialEq { diff --git a/bindgen-tests/tests/expectations/tests/derive-partialeq-bitfield.rs b/bindgen-tests/tests/expectations/tests/derive-partialeq-bitfield.rs index 6f474165ad..eaf3f45e5f 100644 --- a/bindgen-tests/tests/expectations/tests/derive-partialeq-bitfield.rs +++ b/bindgen-tests/tests/expectations/tests/derive-partialeq-bitfield.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,28 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -94,20 +98,12 @@ pub struct C { fn bindgen_test_layout_C() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 204usize, - concat!("Size of: ", stringify!(C)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); + assert_eq!(::std::mem::size_of::(), 204usize, "Size of C"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of C"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).large_array) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(large_array)), + "Offset of field: C::large_array", ); } impl Default for C { diff --git a/bindgen-tests/tests/expectations/tests/derive-partialeq-core.rs b/bindgen-tests/tests/expectations/tests/derive-partialeq-core.rs index b535256cec..3a7639f9de 100644 --- a/bindgen-tests/tests/expectations/tests/derive-partialeq-core.rs +++ b/bindgen-tests/tests/expectations/tests/derive-partialeq-core.rs @@ -9,20 +9,12 @@ pub struct C { fn bindgen_test_layout_C() { const UNINIT: ::core::mem::MaybeUninit = ::core::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::core::mem::size_of::(), - 1680usize, - concat!("Size of: ", stringify!(C)), - ); - assert_eq!( - ::core::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); + assert_eq!(::core::mem::size_of::(), 1680usize, "Size of C"); + assert_eq!(::core::mem::align_of::(), 4usize, "Alignment of C"); assert_eq!( unsafe { ::core::ptr::addr_of!((*ptr).large_array) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(large_array)), + "Offset of field: C::large_array", ); } impl Default for C { diff --git a/bindgen-tests/tests/expectations/tests/derive-partialeq-pointer.rs b/bindgen-tests/tests/expectations/tests/derive-partialeq-pointer.rs index 3baa2daaad..3e48e5d8ce 100644 --- a/bindgen-tests/tests/expectations/tests/derive-partialeq-pointer.rs +++ b/bindgen-tests/tests/expectations/tests/derive-partialeq-pointer.rs @@ -4,26 +4,12 @@ pub struct Bar { pub b: *mut a, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::b"][::std::mem::offset_of!(Bar, b) - 0usize]; +}; impl Default for Bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -43,19 +29,11 @@ pub struct c { pub union c__bindgen_ty_1 { pub _address: u8, } -#[test] -fn bindgen_test_layout_c__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(c__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(c__bindgen_ty_1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of c__bindgen_ty_1"][::std::mem::size_of::() - 1usize]; + ["Alignment of c__bindgen_ty_1"][::std::mem::align_of::() - 1usize]; +}; impl Default for c__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -65,15 +43,11 @@ impl Default for c__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_c() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(c))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(c)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of c"][::std::mem::size_of::() - 1usize]; + ["Alignment of c"][::std::mem::align_of::() - 1usize]; +}; impl Default for c { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -88,22 +62,12 @@ impl Default for c { pub struct a { pub d: c, } -#[test] -fn bindgen_test_layout_a() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(a))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(a), "::", stringify!(d)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of a"][::std::mem::size_of::() - 1usize]; + ["Alignment of a"][::std::mem::align_of::() - 1usize]; + ["Offset of field: a::d"][::std::mem::offset_of!(a, d) - 0usize]; +}; impl Default for a { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-partialeq-union.rs b/bindgen-tests/tests/expectations/tests/derive-partialeq-union.rs index 61b1a4b1b5..0365c765eb 100644 --- a/bindgen-tests/tests/expectations/tests/derive-partialeq-union.rs +++ b/bindgen-tests/tests/expectations/tests/derive-partialeq-union.rs @@ -6,41 +6,21 @@ pub union ShouldNotDerivePartialEq { pub a: ::std::os::raw::c_char, pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_ShouldNotDerivePartialEq() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(ShouldNotDerivePartialEq)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ShouldNotDerivePartialEq)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldNotDerivePartialEq), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldNotDerivePartialEq), - "::", - stringify!(b), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ShouldNotDerivePartialEq", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of ShouldNotDerivePartialEq", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: ShouldNotDerivePartialEq::a", + ][::std::mem::offset_of!(ShouldNotDerivePartialEq, a) - 0usize]; + [ + "Offset of field: ShouldNotDerivePartialEq::b", + ][::std::mem::offset_of!(ShouldNotDerivePartialEq, b) - 0usize]; +}; impl Default for ShouldNotDerivePartialEq { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/derive-partialeq-union_1_0.rs b/bindgen-tests/tests/expectations/tests/derive-partialeq-union_1_0.rs deleted file mode 100644 index 308b6a650b..0000000000 --- a/bindgen-tests/tests/expectations/tests/derive-partialeq-union_1_0.rs +++ /dev/null @@ -1,106 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -/// This should manually derive PartialEq. -#[repr(C)] -#[derive(Copy)] -pub struct ShouldDerivePartialEq { - pub a: __BindgenUnionField<[::std::os::raw::c_char; 150usize]>, - pub b: __BindgenUnionField<::std::os::raw::c_int>, - pub bindgen_union_field: [u32; 38usize], -} -#[test] -fn bindgen_test_layout_ShouldDerivePartialEq() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 152usize, - concat!("Size of: ", stringify!(ShouldDerivePartialEq)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ShouldDerivePartialEq)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldDerivePartialEq), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldDerivePartialEq), - "::", - stringify!(b), - ), - ); -} -impl Clone for ShouldDerivePartialEq { - fn clone(&self) -> Self { - *self - } -} -impl Default for ShouldDerivePartialEq { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -impl ::std::cmp::PartialEq for ShouldDerivePartialEq { - fn eq(&self, other: &ShouldDerivePartialEq) -> bool { - &self.bindgen_union_field[..] == &other.bindgen_union_field[..] - } -} diff --git a/bindgen-tests/tests/expectations/tests/disable-nested-struct-naming.rs b/bindgen-tests/tests/expectations/tests/disable-nested-struct-naming.rs index db942db300..757e0481aa 100644 --- a/bindgen-tests/tests/expectations/tests/disable-nested-struct-naming.rs +++ b/bindgen-tests/tests/expectations/tests/disable-nested-struct-naming.rs @@ -27,141 +27,55 @@ pub struct bar1__bindgen_ty_1__bindgen_ty_1 { pub struct bar4 { pub x4: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_bar4() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(bar4)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar4)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x4) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar4), "::", stringify!(x4)), - ); -} -#[test] -fn bindgen_test_layout_bar1__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(bar1__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar1__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x3) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(bar1__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(x3), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b4) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(bar1__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(b4), - ), - ); -} -#[test] -fn bindgen_test_layout_bar1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(bar1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x2) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(bar1__bindgen_ty_1), - "::", - stringify!(x2), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b3) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(bar1__bindgen_ty_1), - "::", - stringify!(b3), - ), - ); -} -#[test] -fn bindgen_test_layout_bar1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(bar1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x1) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar1), "::", stringify!(x1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b2) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(bar1), "::", stringify!(b2)), - ); -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b1) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(b1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar4"][::std::mem::size_of::() - 4usize]; + ["Alignment of bar4"][::std::mem::align_of::() - 4usize]; + ["Offset of field: bar4::x4"][::std::mem::offset_of!(bar4, x4) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of bar1__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of bar1__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: bar1__bindgen_ty_1__bindgen_ty_1::x3", + ][::std::mem::offset_of!(bar1__bindgen_ty_1__bindgen_ty_1, x3) - 0usize]; + [ + "Offset of field: bar1__bindgen_ty_1__bindgen_ty_1::b4", + ][::std::mem::offset_of!(bar1__bindgen_ty_1__bindgen_ty_1, b4) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of bar1__bindgen_ty_1", + ][::std::mem::size_of::() - 12usize]; + [ + "Alignment of bar1__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: bar1__bindgen_ty_1::x2", + ][::std::mem::offset_of!(bar1__bindgen_ty_1, x2) - 0usize]; + [ + "Offset of field: bar1__bindgen_ty_1::b3", + ][::std::mem::offset_of!(bar1__bindgen_ty_1, b3) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar1"][::std::mem::size_of::() - 16usize]; + ["Alignment of bar1"][::std::mem::align_of::() - 4usize]; + ["Offset of field: bar1::x1"][::std::mem::offset_of!(bar1, x1) - 0usize]; + ["Offset of field: bar1::b2"][::std::mem::offset_of!(bar1, b2) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 16usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::b1"][::std::mem::offset_of!(foo, b1) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct _bindgen_ty_1 { @@ -177,71 +91,32 @@ pub struct _bindgen_ty_1__bindgen_ty_1 { pub struct baz { pub x: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_baz() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(baz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(baz), "::", stringify!(x)), - ); -} -#[test] -fn bindgen_test_layout__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit<_bindgen_ty_1__bindgen_ty_1> = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::<_bindgen_ty_1__bindgen_ty_1>(), - 4usize, - concat!("Size of: ", stringify!(_bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::<_bindgen_ty_1__bindgen_ty_1>(), - 4usize, - concat!("Alignment of ", stringify!(_bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(_bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(b), - ), - ); -} -#[test] -fn bindgen_test_layout__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit<_bindgen_ty_1> = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::<_bindgen_ty_1>(), - 4usize, - concat!("Size of: ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::<_bindgen_ty_1>(), - 4usize, - concat!("Alignment of ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).anon2) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(_bindgen_ty_1), "::", stringify!(anon2)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of baz"][::std::mem::size_of::() - 4usize]; + ["Alignment of baz"][::std::mem::align_of::() - 4usize]; + ["Offset of field: baz::x"][::std::mem::offset_of!(baz, x) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of _bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::<_bindgen_ty_1__bindgen_ty_1>() - 4usize]; + [ + "Alignment of _bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::<_bindgen_ty_1__bindgen_ty_1>() - 4usize]; + [ + "Offset of field: _bindgen_ty_1__bindgen_ty_1::b", + ][::std::mem::offset_of!(_bindgen_ty_1__bindgen_ty_1, b) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of _bindgen_ty_1"][::std::mem::size_of::<_bindgen_ty_1>() - 4usize]; + ["Alignment of _bindgen_ty_1"][::std::mem::align_of::<_bindgen_ty_1>() - 4usize]; + [ + "Offset of field: _bindgen_ty_1::anon2", + ][::std::mem::offset_of!(_bindgen_ty_1, anon2) - 0usize]; +}; +unsafe extern "C" { pub static mut anon1: _bindgen_ty_1; } diff --git a/bindgen-tests/tests/expectations/tests/disable-untagged-union.rs b/bindgen-tests/tests/expectations/tests/disable-untagged-union.rs index d507c70a3a..60636280e4 100644 --- a/bindgen-tests/tests/expectations/tests/disable-untagged-union.rs +++ b/bindgen-tests/tests/expectations/tests/disable-untagged-union.rs @@ -49,28 +49,10 @@ pub struct Foo { pub baz: __BindgenUnionField<::std::os::raw::c_uint>, pub bindgen_union_field: u32, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo::bar"][::std::mem::offset_of!(Foo, bar) - 0usize]; + ["Offset of field: Foo::baz"][::std::mem::offset_of!(Foo, baz) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/divide-by-zero-in-struct-layout.rs b/bindgen-tests/tests/expectations/tests/divide-by-zero-in-struct-layout.rs index 707c2d56bc..e01a9b3c72 100644 --- a/bindgen-tests/tests/expectations/tests/divide-by-zero-in-struct-layout.rs +++ b/bindgen-tests/tests/expectations/tests/divide-by-zero-in-struct-layout.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] diff --git a/bindgen-tests/tests/expectations/tests/do-not-derive-copy.rs b/bindgen-tests/tests/expectations/tests/do-not-derive-copy.rs index 5d1cf1c547..29ca6d6acf 100644 --- a/bindgen-tests/tests/expectations/tests/do-not-derive-copy.rs +++ b/bindgen-tests/tests/expectations/tests/do-not-derive-copy.rs @@ -4,28 +4,15 @@ pub struct WouldBeCopyButWeAreNotDerivingCopy { pub x: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_WouldBeCopyButWeAreNotDerivingCopy() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WouldBeCopyButWeAreNotDerivingCopy)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WouldBeCopyButWeAreNotDerivingCopy)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WouldBeCopyButWeAreNotDerivingCopy), - "::", - stringify!(x), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of WouldBeCopyButWeAreNotDerivingCopy", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of WouldBeCopyButWeAreNotDerivingCopy", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WouldBeCopyButWeAreNotDerivingCopy::x", + ][::std::mem::offset_of!(WouldBeCopyButWeAreNotDerivingCopy, x) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/doggo-or-null.rs b/bindgen-tests/tests/expectations/tests/doggo-or-null.rs index 395c02043e..972da871d3 100644 --- a/bindgen-tests/tests/expectations/tests/doggo-or-null.rs +++ b/bindgen-tests/tests/expectations/tests/doggo-or-null.rs @@ -4,44 +4,22 @@ pub struct Doggo { pub x: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Doggo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Doggo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Doggo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Doggo), "::", stringify!(x)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Doggo"][::std::mem::size_of::() - 4usize]; + ["Alignment of Doggo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Doggo::x"][::std::mem::offset_of!(Doggo, x) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq)] pub struct Null { pub _address: u8, } -#[test] -fn bindgen_test_layout_Null() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Null)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Null)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Null"][::std::mem::size_of::() - 1usize]; + ["Alignment of Null"][::std::mem::align_of::() - 1usize]; +}; /** This type is an opaque union. Unions can't derive anything interesting like Debug or Default, even if their layout can, because it would require knowing which variant is in use. Opaque unions still end up as a `union` in the Rust @@ -54,19 +32,11 @@ fn bindgen_test_layout_Null() { pub union DoggoOrNull { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_DoggoOrNull() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(DoggoOrNull)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(DoggoOrNull)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of DoggoOrNull"][::std::mem::size_of::() - 4usize]; + ["Alignment of DoggoOrNull"][::std::mem::align_of::() - 4usize]; +}; impl Default for DoggoOrNull { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/duplicated-definition-count.rs b/bindgen-tests/tests/expectations/tests/duplicated-definition-count.rs index 186d32d1f9..86e1edbbf9 100644 --- a/bindgen-tests/tests/expectations/tests/duplicated-definition-count.rs +++ b/bindgen-tests/tests/expectations/tests/duplicated-definition-count.rs @@ -4,20 +4,12 @@ pub struct BitStream { pub _address: u8, } -#[test] -fn bindgen_test_layout_BitStream() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(BitStream)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(BitStream)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of BitStream"][::std::mem::size_of::() - 1usize]; + ["Alignment of BitStream"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN9BitStream5WriteEPKcj"] pub fn BitStream_Write( this: *mut BitStream, @@ -25,7 +17,7 @@ extern "C" { numberOfBytes: ::std::os::raw::c_uint, ); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN9BitStream5WriteEPS_j"] pub fn BitStream_Write1( this: *mut BitStream, @@ -33,7 +25,7 @@ extern "C" { numberOfBits: ::std::os::raw::c_uint, ); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN9BitStream6Write1Ev"] pub fn BitStream_Write11(this: *mut BitStream); } diff --git a/bindgen-tests/tests/expectations/tests/duplicated-namespaces-definitions.rs b/bindgen-tests/tests/expectations/tests/duplicated-namespaces-definitions.rs index afb649d769..775a21ac30 100644 --- a/bindgen-tests/tests/expectations/tests/duplicated-namespaces-definitions.rs +++ b/bindgen-tests/tests/expectations/tests/duplicated-namespaces-definitions.rs @@ -12,31 +12,13 @@ pub mod root { pub foo: ::std::os::raw::c_int, pub baz: bool, } - #[test] - fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Bar::foo"][::std::mem::offset_of!(Bar, foo) - 0usize]; + ["Offset of field: Bar::baz"][::std::mem::offset_of!(Bar, baz) - 4usize]; + }; } pub mod bar { #[allow(unused_imports)] @@ -46,26 +28,12 @@ pub mod root { pub struct Foo { pub ptr: *mut root::foo::Bar, } - #[test] - fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ptr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(ptr)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Foo::ptr"][::std::mem::offset_of!(Foo, ptr) - 0usize]; + }; impl Default for Foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_attributes.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_attributes.rs index 7682884bbb..a1fb1b0cc1 100644 --- a/bindgen-tests/tests/expectations/tests/dynamic_loading_attributes.rs +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_attributes.rs @@ -1,5 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern crate libloading; pub struct TestLib { __library: ::libloading::Library, pub foo: unsafe extern "C" fn( diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_required.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_required.rs index 6fd97e4a46..5c929ffc3d 100644 --- a/bindgen-tests/tests/expectations/tests/dynamic_loading_required.rs +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_required.rs @@ -1,5 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern crate libloading; pub struct TestLib { __library: ::libloading::Library, pub foo: unsafe extern "C" fn( diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_simple.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_simple.rs index cdacf3ab42..9a4cfaf570 100644 --- a/bindgen-tests/tests/expectations/tests/dynamic_loading_simple.rs +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_simple.rs @@ -1,5 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern crate libloading; pub struct TestLib { __library: ::libloading::Library, pub foo: Result< diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_template.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_template.rs index 65c36e4893..1f63a7893f 100644 --- a/bindgen-tests/tests/expectations/tests/dynamic_loading_template.rs +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_template.rs @@ -1,5 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern crate libloading; pub struct TestLib { __library: ::libloading::Library, pub foo: Result< @@ -21,8 +20,8 @@ impl TestLib { L: Into<::libloading::Library>, { let __library = library.into(); - let foo = __library.get(b"foo\0").map(|sym| *sym); - let foo1 = __library.get(b"foo1\0").map(|sym| *sym); + let foo = __library.get(b"_Z3fooIiET_S0_\0").map(|sym| *sym); + let foo1 = __library.get(b"_Z3fooIfET_S0_\0").map(|sym| *sym); Ok(TestLib { __library, foo, foo1 }) } pub unsafe fn foo(&self, x: ::std::os::raw::c_int) -> ::std::os::raw::c_int { diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_required.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_required.rs new file mode 100644 index 0000000000..a96efbe546 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_required.rs @@ -0,0 +1,32 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub struct TestLib { + __library: ::libloading::Library, + pub foo: *mut ::std::os::raw::c_int, + pub baz: *mut *mut ::std::os::raw::c_int, +} +impl TestLib { + pub unsafe fn new

(path: P) -> Result + where + P: AsRef<::std::ffi::OsStr>, + { + let library = ::libloading::Library::new(path)?; + Self::from_library(library) + } + pub unsafe fn from_library(library: L) -> Result + where + L: Into<::libloading::Library>, + { + let __library = library.into(); + let foo = __library.get::<*mut ::std::os::raw::c_int>(b"foo\0").map(|sym| *sym)?; + let baz = __library + .get::<*mut *mut ::std::os::raw::c_int>(b"baz\0") + .map(|sym| *sym)?; + Ok(TestLib { __library, foo, baz }) + } + pub unsafe fn foo(&self) -> *mut ::std::os::raw::c_int { + self.foo + } + pub unsafe fn baz(&self) -> *mut *mut ::std::os::raw::c_int { + self.baz + } +} diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_simple.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_simple.rs new file mode 100644 index 0000000000..ced70dbdba --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_simple.rs @@ -0,0 +1,32 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub struct TestLib { + __library: ::libloading::Library, + pub foo: Result<*mut ::std::os::raw::c_int, ::libloading::Error>, + pub baz: Result<*mut *mut ::std::os::raw::c_int, ::libloading::Error>, +} +impl TestLib { + pub unsafe fn new

(path: P) -> Result + where + P: AsRef<::std::ffi::OsStr>, + { + let library = ::libloading::Library::new(path)?; + Self::from_library(library) + } + pub unsafe fn from_library(library: L) -> Result + where + L: Into<::libloading::Library>, + { + let __library = library.into(); + let foo = __library.get::<*mut ::std::os::raw::c_int>(b"foo\0").map(|sym| *sym); + let baz = __library + .get::<*mut *mut ::std::os::raw::c_int>(b"baz\0") + .map(|sym| *sym); + Ok(TestLib { __library, foo, baz }) + } + pub unsafe fn foo(&self) -> *mut ::std::os::raw::c_int { + *self.foo.as_ref().expect("Expected variable, got error.") + } + pub unsafe fn baz(&self) -> *mut *mut ::std::os::raw::c_int { + *self.baz.as_ref().expect("Expected variable, got error.") + } +} diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_with_allowlist.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_with_allowlist.rs new file mode 100644 index 0000000000..3f29e73814 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_variable_with_allowlist.rs @@ -0,0 +1,30 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub struct TestLib { + __library: ::libloading::Library, + pub foo: Result<*mut ::std::os::raw::c_int, ::libloading::Error>, + pub bar: Result<*mut ::std::os::raw::c_int, ::libloading::Error>, +} +impl TestLib { + pub unsafe fn new

(path: P) -> Result + where + P: AsRef<::std::ffi::OsStr>, + { + let library = ::libloading::Library::new(path)?; + Self::from_library(library) + } + pub unsafe fn from_library(library: L) -> Result + where + L: Into<::libloading::Library>, + { + let __library = library.into(); + let foo = __library.get::<*mut ::std::os::raw::c_int>(b"foo\0").map(|sym| *sym); + let bar = __library.get::<*mut ::std::os::raw::c_int>(b"bar\0").map(|sym| *sym); + Ok(TestLib { __library, foo, bar }) + } + pub unsafe fn foo(&self) -> *mut ::std::os::raw::c_int { + *self.foo.as_ref().expect("Expected variable, got error.") + } + pub unsafe fn bar(&self) -> *mut ::std::os::raw::c_int { + *self.bar.as_ref().expect("Expected variable, got error.") + } +} diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_with_allowlist.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_with_allowlist.rs index 06fffc3d47..34ebe8d9a5 100644 --- a/bindgen-tests/tests/expectations/tests/dynamic_loading_with_allowlist.rs +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_with_allowlist.rs @@ -1,5 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern crate libloading; pub struct TestLib { __library: ::libloading::Library, pub foo: Result< @@ -28,9 +27,9 @@ impl TestLib { L: Into<::libloading::Library>, { let __library = library.into(); - let foo = __library.get(b"foo\0").map(|sym| *sym); - let baz = __library.get(b"baz\0").map(|sym| *sym); - let bazz = __library.get(b"bazz\0").map(|sym| *sym); + let foo = __library.get(b"_Z3fooPv\0").map(|sym| *sym); + let baz = __library.get(b"_Z3bazPv\0").map(|sym| *sym); + let bazz = __library.get(b"_Z4bazziz\0").map(|sym| *sym); Ok(TestLib { __library, foo, diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_with_blocklist.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_with_blocklist.rs index 4a523db856..8c86674f7a 100644 --- a/bindgen-tests/tests/expectations/tests/dynamic_loading_with_blocklist.rs +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_with_blocklist.rs @@ -4,31 +4,21 @@ pub struct X { pub _x: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_X() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(X))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(X)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr)._x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(X), "::", stringify!(_x)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of X"][::std::mem::size_of::() - 4usize]; + ["Alignment of X"][::std::mem::align_of::() - 4usize]; + ["Offset of field: X::_x"][::std::mem::offset_of!(X, _x) - 0usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN1X13some_functionEv"] pub fn X_some_function(this: *mut X); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1X19some_other_functionEv"] pub fn X_some_other_function(this: *mut X); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1XC1Ei"] pub fn X_X(this: *mut X, x: ::std::os::raw::c_int); } @@ -48,7 +38,6 @@ impl X { __bindgen_tmp.assume_init() } } -extern crate libloading; pub struct TestLib { __library: ::libloading::Library, pub foo: Result< @@ -73,8 +62,8 @@ impl TestLib { L: Into<::libloading::Library>, { let __library = library.into(); - let foo = __library.get(b"foo\0").map(|sym| *sym); - let bar = __library.get(b"bar\0").map(|sym| *sym); + let foo = __library.get(b"_Z3fooPv\0").map(|sym| *sym); + let bar = __library.get(b"_Z3barPv\0").map(|sym| *sym); Ok(TestLib { __library, foo, bar }) } pub unsafe fn foo(&self, x: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int { diff --git a/bindgen-tests/tests/expectations/tests/dynamic_loading_with_class.rs b/bindgen-tests/tests/expectations/tests/dynamic_loading_with_class.rs index 2d17952408..65ff2b2f72 100644 --- a/bindgen-tests/tests/expectations/tests/dynamic_loading_with_class.rs +++ b/bindgen-tests/tests/expectations/tests/dynamic_loading_with_class.rs @@ -4,31 +4,21 @@ pub struct A { pub _x: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr)._x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(_x)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 4usize]; + ["Alignment of A"][::std::mem::align_of::() - 4usize]; + ["Offset of field: A::_x"][::std::mem::offset_of!(A, _x) - 0usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN1A13some_functionEv"] pub fn A_some_function(this: *mut A); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1A19some_other_functionEv"] pub fn A_some_other_function(this: *mut A); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1AC1Ei"] pub fn A_A(this: *mut A, x: ::std::os::raw::c_int); } @@ -48,7 +38,6 @@ impl A { __bindgen_tmp.assume_init() } } -extern crate libloading; pub struct TestLib { __library: ::libloading::Library, pub foo: Result< @@ -70,8 +59,8 @@ impl TestLib { L: Into<::libloading::Library>, { let __library = library.into(); - let foo = __library.get(b"foo\0").map(|sym| *sym); - let bar = __library.get(b"bar\0").map(|sym| *sym); + let foo = __library.get(b"_Z3fooPv\0").map(|sym| *sym); + let bar = __library.get(b"_Z3barv\0").map(|sym| *sym); Ok(TestLib { __library, foo, bar }) } pub unsafe fn foo(&self, x: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int { diff --git a/bindgen-tests/tests/expectations/tests/elaborated.rs b/bindgen-tests/tests/expectations/tests/elaborated.rs index 80bf30f89a..81c0733089 100644 --- a/bindgen-tests/tests/expectations/tests/elaborated.rs +++ b/bindgen-tests/tests/expectations/tests/elaborated.rs @@ -1,6 +1,6 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] pub type whatever_whatever_t = ::std::os::raw::c_int; -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z9somethingPKi"] pub fn something(wat: *const whatever_whatever_t); } diff --git a/bindgen-tests/tests/expectations/tests/enum-default-bitfield.rs b/bindgen-tests/tests/expectations/tests/enum-default-bitfield.rs index 0d3829de20..b7b14fbc1c 100644 --- a/bindgen-tests/tests/expectations/tests/enum-default-bitfield.rs +++ b/bindgen-tests/tests/expectations/tests/enum-default-bitfield.rs @@ -35,26 +35,12 @@ impl ::std::ops::BitAndAssign for foo__bindgen_ty_1 { #[repr(transparent)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo__bindgen_ty_1(pub ::std::os::raw::c_uint); -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::member"][::std::mem::offset_of!(foo, member) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -66,8 +52,6 @@ impl Default for foo { } impl Foo { pub const Bar: Foo = Foo(0); -} -impl Foo { pub const Qux: Foo = Foo(1); } impl ::std::ops::BitOr for Foo { @@ -106,8 +90,6 @@ pub mod Neg { } impl NoDebug { pub const NoDebug1: NoDebug = NoDebug(0); -} -impl NoDebug { pub const NoDebug2: NoDebug = NoDebug(1); } impl ::std::ops::BitOr for NoDebug { @@ -142,8 +124,6 @@ impl ::std::ops::BitAndAssign for NoDebug { pub struct NoDebug(pub ::std::os::raw::c_uint); impl Debug { pub const Debug1: Debug = Debug(0); -} -impl Debug { pub const Debug2: Debug = Debug(1); } impl ::std::ops::BitOr for Debug { diff --git a/bindgen-tests/tests/expectations/tests/enum-default-consts.rs b/bindgen-tests/tests/expectations/tests/enum-default-consts.rs index a63be965bf..af51864c2c 100644 --- a/bindgen-tests/tests/expectations/tests/enum-default-consts.rs +++ b/bindgen-tests/tests/expectations/tests/enum-default-consts.rs @@ -7,26 +7,12 @@ pub struct foo { pub const foo_FOO_A: foo__bindgen_ty_1 = 0; pub const foo_FOO_B: foo__bindgen_ty_1 = 1; pub type foo__bindgen_ty_1 = ::std::os::raw::c_uint; -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::member"][::std::mem::offset_of!(foo, member) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/enum-default-module.rs b/bindgen-tests/tests/expectations/tests/enum-default-module.rs index 9774135d5c..cc09d49425 100644 --- a/bindgen-tests/tests/expectations/tests/enum-default-module.rs +++ b/bindgen-tests/tests/expectations/tests/enum-default-module.rs @@ -9,26 +9,12 @@ pub mod foo__bindgen_ty_1 { pub const FOO_A: Type = 0; pub const FOO_B: Type = 1; } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::member"][::std::mem::offset_of!(foo, member) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/enum-default-rust.rs b/bindgen-tests/tests/expectations/tests/enum-default-rust.rs index 27ea5a1694..f9a99166de 100644 --- a/bindgen-tests/tests/expectations/tests/enum-default-rust.rs +++ b/bindgen-tests/tests/expectations/tests/enum-default-rust.rs @@ -12,26 +12,12 @@ pub enum foo__bindgen_ty_1 { FOO_A = 0, FOO_B = 1, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::member"][::std::mem::offset_of!(foo, member) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/enum-doc-bitfield.rs b/bindgen-tests/tests/expectations/tests/enum-doc-bitfield.rs index e6e9ffaa65..33eec3e44f 100644 --- a/bindgen-tests/tests/expectations/tests/enum-doc-bitfield.rs +++ b/bindgen-tests/tests/expectations/tests/enum-doc-bitfield.rs @@ -2,25 +2,15 @@ impl B { /// Document field with three slashes pub const VAR_A: B = B(0); -} -impl B { - /// Document field with preceeding star + /// Document field with preceding star pub const VAR_B: B = B(1); -} -impl B { - /// Document field with preceeding exclamation + /// Document field with preceding exclamation pub const VAR_C: B = B(2); -} -impl B { ///< Document field with following star pub const VAR_D: B = B(3); -} -impl B { ///< Document field with following exclamation pub const VAR_E: B = B(4); -} -impl B { - /** Document field with preceeding star, with a loong long multiline + /** Document field with preceding star, with a loong long multiline comment. Very interesting documentation, definitely.*/ diff --git a/bindgen-tests/tests/expectations/tests/enum-doc-mod.rs b/bindgen-tests/tests/expectations/tests/enum-doc-mod.rs index c54410e271..2b18b35df0 100644 --- a/bindgen-tests/tests/expectations/tests/enum-doc-mod.rs +++ b/bindgen-tests/tests/expectations/tests/enum-doc-mod.rs @@ -4,15 +4,15 @@ pub mod B { pub type Type = ::std::os::raw::c_uint; /// Document field with three slashes pub const VAR_A: Type = 0; - /// Document field with preceeding star + /// Document field with preceding star pub const VAR_B: Type = 1; - /// Document field with preceeding exclamation + /// Document field with preceding exclamation pub const VAR_C: Type = 2; ///< Document field with following star pub const VAR_D: Type = 3; ///< Document field with following exclamation pub const VAR_E: Type = 4; - /** Document field with preceeding star, with a loong long multiline + /** Document field with preceding star, with a loong long multiline comment. Very interesting documentation, definitely.*/ diff --git a/bindgen-tests/tests/expectations/tests/enum-doc-rusty.rs b/bindgen-tests/tests/expectations/tests/enum-doc-rusty.rs index a83d2dc458..3eec0759c5 100644 --- a/bindgen-tests/tests/expectations/tests/enum-doc-rusty.rs +++ b/bindgen-tests/tests/expectations/tests/enum-doc-rusty.rs @@ -5,15 +5,15 @@ pub enum B { /// Document field with three slashes VAR_A = 0, - /// Document field with preceeding star + /// Document field with preceding star VAR_B = 1, - /// Document field with preceeding exclamation + /// Document field with preceding exclamation VAR_C = 2, ///< Document field with following star VAR_D = 3, ///< Document field with following exclamation VAR_E = 4, - /** Document field with preceeding star, with a loong long multiline + /** Document field with preceding star, with a loong long multiline comment. Very interesting documentation, definitely.*/ diff --git a/bindgen-tests/tests/expectations/tests/enum-doc.rs b/bindgen-tests/tests/expectations/tests/enum-doc.rs index ee0ca23bff..98a7eed8f8 100644 --- a/bindgen-tests/tests/expectations/tests/enum-doc.rs +++ b/bindgen-tests/tests/expectations/tests/enum-doc.rs @@ -1,15 +1,15 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] /// Document field with three slashes pub const B_VAR_A: B = 0; -/// Document field with preceeding star +/// Document field with preceding star pub const B_VAR_B: B = 1; -/// Document field with preceeding exclamation +/// Document field with preceding exclamation pub const B_VAR_C: B = 2; ///< Document field with following star pub const B_VAR_D: B = 3; ///< Document field with following exclamation pub const B_VAR_E: B = 4; -/** Document field with preceeding star, with a loong long multiline +/** Document field with preceding star, with a loong long multiline comment. Very interesting documentation, definitely.*/ diff --git a/bindgen-tests/tests/expectations/tests/enum-no-debug-rust.rs b/bindgen-tests/tests/expectations/tests/enum-no-debug-rust.rs index 6050d25ad3..b728dfc898 100644 --- a/bindgen-tests/tests/expectations/tests/enum-no-debug-rust.rs +++ b/bindgen-tests/tests/expectations/tests/enum-no-debug-rust.rs @@ -12,26 +12,12 @@ pub enum foo__bindgen_ty_1 { FOO_A = 0, FOO_B = 1, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::member"][::std::mem::offset_of!(foo, member) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/enum.rs b/bindgen-tests/tests/expectations/tests/enum.rs index 69422fb34b..820182125a 100644 --- a/bindgen-tests/tests/expectations/tests/enum.rs +++ b/bindgen-tests/tests/expectations/tests/enum.rs @@ -7,26 +7,12 @@ pub struct foo { pub const foo_FOO_A: foo__bindgen_ty_1 = 0; pub const foo_FOO_B: foo__bindgen_ty_1 = 1; pub type foo__bindgen_ty_1 = ::std::os::raw::c_uint; -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::member"][::std::mem::offset_of!(foo, member) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/enum_and_vtable_mangling.rs b/bindgen-tests/tests/expectations/tests/enum_and_vtable_mangling.rs index c450c7b2d9..0a7e16d6dd 100644 --- a/bindgen-tests/tests/expectations/tests/enum_and_vtable_mangling.rs +++ b/bindgen-tests/tests/expectations/tests/enum_and_vtable_mangling.rs @@ -17,22 +17,12 @@ pub struct C { pub vtable_: *const C__bindgen_vtable, pub i: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 16usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(i)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 16usize]; + ["Alignment of C"][::std::mem::align_of::() - 8usize]; + ["Offset of field: C::i"][::std::mem::offset_of!(C, i) - 8usize]; +}; impl Default for C { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -42,7 +32,7 @@ impl Default for C { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1C5matchEv"] pub fn C_match(this: *mut ::std::os::raw::c_void); } diff --git a/bindgen-tests/tests/expectations/tests/explicit-padding.rs b/bindgen-tests/tests/expectations/tests/explicit-padding.rs index 14d46c8120..ec21399106 100644 --- a/bindgen-tests/tests/expectations/tests/explicit-padding.rs +++ b/bindgen-tests/tests/expectations/tests/explicit-padding.rs @@ -8,36 +8,14 @@ pub struct pad_me { pub third: u16, pub __bindgen_padding_1: [u8; 2usize], } -#[test] -fn bindgen_test_layout_pad_me() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(pad_me)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(pad_me)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).first) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(pad_me), "::", stringify!(first)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).second) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(pad_me), "::", stringify!(second)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).third) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(pad_me), "::", stringify!(third)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of pad_me"][::std::mem::size_of::() - 12usize]; + ["Alignment of pad_me"][::std::mem::align_of::() - 4usize]; + ["Offset of field: pad_me::first"][::std::mem::offset_of!(pad_me, first) - 0usize]; + ["Offset of field: pad_me::second"][::std::mem::offset_of!(pad_me, second) - 4usize]; + ["Offset of field: pad_me::third"][::std::mem::offset_of!(pad_me, third) - 8usize]; +}; #[repr(C)] #[derive(Copy, Clone)] pub union dont_pad_me { @@ -45,36 +23,20 @@ pub union dont_pad_me { pub second: u32, pub third: u16, } -#[test] -fn bindgen_test_layout_dont_pad_me() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(dont_pad_me)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(dont_pad_me)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).first) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(dont_pad_me), "::", stringify!(first)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).second) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(dont_pad_me), "::", stringify!(second)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).third) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(dont_pad_me), "::", stringify!(third)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of dont_pad_me"][::std::mem::size_of::() - 4usize]; + ["Alignment of dont_pad_me"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: dont_pad_me::first", + ][::std::mem::offset_of!(dont_pad_me, first) - 0usize]; + [ + "Offset of field: dont_pad_me::second", + ][::std::mem::offset_of!(dont_pad_me, second) - 0usize]; + [ + "Offset of field: dont_pad_me::third", + ][::std::mem::offset_of!(dont_pad_me, third) - 0usize]; +}; impl Default for dont_pad_me { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/extern-const-struct.rs b/bindgen-tests/tests/expectations/tests/extern-const-struct.rs index db62de1460..c449e1a019 100644 --- a/bindgen-tests/tests/expectations/tests/extern-const-struct.rs +++ b/bindgen-tests/tests/expectations/tests/extern-const-struct.rs @@ -8,20 +8,12 @@ pub struct nsFoo { fn bindgen_test_layout_nsFoo() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1600usize, - concat!("Size of: ", stringify!(nsFoo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(nsFoo)), - ); + assert_eq!(::std::mem::size_of::(), 1600usize, "Size of nsFoo"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of nsFoo"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).details) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(nsFoo), "::", stringify!(details)), + "Offset of field: nsFoo::details", ); } impl Default for nsFoo { diff --git a/bindgen-tests/tests/expectations/tests/extern_blocks_post_1_82.rs b/bindgen-tests/tests/expectations/tests/extern_blocks_post_1_82.rs new file mode 100644 index 0000000000..a322df78ce --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/extern_blocks_post_1_82.rs @@ -0,0 +1,7 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +unsafe extern "C" { + pub fn cool_function(i: ::std::os::raw::c_int, c: ::std::os::raw::c_char); +} +unsafe extern "C" { + pub static mut cool_static: ::std::os::raw::c_int; +} diff --git a/bindgen-tests/tests/expectations/tests/extern_blocks_pre_1_82.rs b/bindgen-tests/tests/expectations/tests/extern_blocks_pre_1_82.rs new file mode 100644 index 0000000000..9f684084ba --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/extern_blocks_pre_1_82.rs @@ -0,0 +1,7 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +extern "C" { + pub fn cool_function(i: ::std::os::raw::c_int, c: ::std::os::raw::c_char); +} +extern "C" { + pub static mut cool_static: ::std::os::raw::c_int; +} diff --git a/bindgen-tests/tests/expectations/tests/field-visibility-callback.rs b/bindgen-tests/tests/expectations/tests/field-visibility-callback.rs index 31d6335700..aebc04f03b 100644 --- a/bindgen-tests/tests/expectations/tests/field-visibility-callback.rs +++ b/bindgen-tests/tests/expectations/tests/field-visibility-callback.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -92,31 +154,15 @@ pub struct my_struct { _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, __bindgen_padding_0: [u8; 3usize], } -#[test] -fn bindgen_test_layout_my_struct() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(my_struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(my_struct)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(my_struct), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).private_b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(my_struct), "::", stringify!(private_b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of my_struct"][::std::mem::size_of::() - 12usize]; + ["Alignment of my_struct"][::std::mem::align_of::() - 4usize]; + ["Offset of field: my_struct::a"][::std::mem::offset_of!(my_struct, a) - 0usize]; + [ + "Offset of field: my_struct::private_b", + ][::std::mem::offset_of!(my_struct, private_b) - 4usize]; +}; impl my_struct { #[inline] pub fn c(&self) -> ::std::os::raw::c_int { @@ -130,6 +176,31 @@ impl my_struct { } } #[inline] + pub unsafe fn c_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_c_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] fn private_d(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } } @@ -141,6 +212,31 @@ impl my_struct { } } #[inline] + unsafe fn private_d_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) + as u32, + ) + } + } + #[inline] + unsafe fn set_private_d_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] fn new_bitfield_1( c: ::std::os::raw::c_int, private_d: ::std::os::raw::c_int, diff --git a/bindgen-tests/tests/expectations/tests/field-visibility.rs b/bindgen-tests/tests/expectations/tests/field-visibility.rs index c898d60b75..3e43755a57 100644 --- a/bindgen-tests/tests/expectations/tests/field-visibility.rs +++ b/bindgen-tests/tests/expectations/tests/field-visibility.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[repr(align(4))] @@ -91,19 +153,11 @@ pub struct my_struct1 { _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, __bindgen_padding_0: [u8; 3usize], } -#[test] -fn bindgen_test_layout_my_struct1() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(my_struct1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(my_struct1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of my_struct1"][::std::mem::size_of::() - 4usize]; + ["Alignment of my_struct1"][::std::mem::align_of::() - 4usize]; +}; impl my_struct1 { #[inline] fn a(&self) -> ::std::os::raw::c_int { @@ -117,6 +171,31 @@ impl my_struct1 { } } #[inline] + unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u32, + ) + } + } + #[inline] + unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] fn new_bitfield_1(a: ::std::os::raw::c_int) -> __BindgenBitfieldUnit<[u8; 1usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); __bindgen_bitfield_unit @@ -139,19 +218,11 @@ pub struct my_struct2 { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub __bindgen_padding_0: [u8; 3usize], } -#[test] -fn bindgen_test_layout_my_struct2() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(my_struct2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(my_struct2)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of my_struct2"][::std::mem::size_of::() - 4usize]; + ["Alignment of my_struct2"][::std::mem::align_of::() - 4usize]; +}; impl my_struct2 { #[inline] pub fn a(&self) -> ::std::os::raw::c_int { @@ -165,6 +236,31 @@ impl my_struct2 { } } #[inline] + pub unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( a: ::std::os::raw::c_int, ) -> __BindgenBitfieldUnit<[u8; 1usize]> { diff --git a/bindgen-tests/tests/expectations/tests/fit-macro-constant-types-signed.rs b/bindgen-tests/tests/expectations/tests/fit-macro-constant-types-signed.rs index 0602f7714a..d4ad5e0fcc 100644 --- a/bindgen-tests/tests/expectations/tests/fit-macro-constant-types-signed.rs +++ b/bindgen-tests/tests/expectations/tests/fit-macro-constant-types-signed.rs @@ -30,7 +30,7 @@ pub const MIN_U32_Minus1: i8 = -1; pub const MIN_I32_Minus1: i64 = -2147483649; pub const LONG12: i64 = 123456789012; pub const LONG_12: i64 = -123456789012; -extern "C" { +unsafe extern "C" { pub fn foo( arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, @@ -40,7 +40,7 @@ extern "C" { arg6: ::std::os::raw::c_schar, ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { pub fn bar( arg1: ::std::os::raw::c_long, arg2: ::std::os::raw::c_longlong, diff --git a/bindgen-tests/tests/expectations/tests/fit-macro-constant-types.rs b/bindgen-tests/tests/expectations/tests/fit-macro-constant-types.rs index f5d2a56ff2..5542a645da 100644 --- a/bindgen-tests/tests/expectations/tests/fit-macro-constant-types.rs +++ b/bindgen-tests/tests/expectations/tests/fit-macro-constant-types.rs @@ -30,7 +30,7 @@ pub const MIN_U32_Minus1: i8 = -1; pub const MIN_I32_Minus1: i64 = -2147483649; pub const LONG12: u64 = 123456789012; pub const LONG_12: i64 = -123456789012; -extern "C" { +unsafe extern "C" { pub fn foo( arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, @@ -40,7 +40,7 @@ extern "C" { arg6: ::std::os::raw::c_schar, ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { pub fn bar( arg1: ::std::os::raw::c_long, arg2: ::std::os::raw::c_longlong, diff --git a/bindgen-tests/tests/expectations/tests/flexarray.rs b/bindgen-tests/tests/expectations/tests/flexarray.rs new file mode 100644 index 0000000000..b9c800366e --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/flexarray.rs @@ -0,0 +1,555 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#![cfg(feature = "nightly")] +#![feature(ptr_metadata, layout_for_ptr)] +#[repr(C)] +#[derive(Default)] +pub struct __IncompleteArrayField(::std::marker::PhantomData, [T; 0]); +impl __IncompleteArrayField { + #[inline] + pub const fn new() -> Self { + __IncompleteArrayField(::std::marker::PhantomData, []) + } + #[inline] + pub fn as_ptr(&self) -> *const T { + self as *const _ as *const T + } + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T { + self as *mut _ as *mut T + } + #[inline] + pub unsafe fn as_slice(&self, len: usize) -> &[T] { + ::std::slice::from_raw_parts(self.as_ptr(), len) + } + #[inline] + pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { + ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) + } +} +impl ::std::fmt::Debug for __IncompleteArrayField { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + fmt.write_str("__IncompleteArrayField") + } +} +#[repr(C)] +#[derive(Debug, Default)] +pub struct flexarray { + pub count: ::std::os::raw::c_int, + pub data: FAM, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of flexarray"][::std::mem::size_of::() - 4usize]; + ["Alignment of flexarray"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: flexarray::count", + ][::std::mem::offset_of!(flexarray, count) - 0usize]; + [ + "Offset of field: flexarray::data", + ][::std::mem::offset_of!(flexarray, data) - 4usize]; +}; +impl flexarray<[::std::os::raw::c_int]> { + pub fn layout(len: usize) -> ::std::alloc::Layout { + unsafe { + let p: *const Self = ::std::ptr::from_raw_parts( + ::std::ptr::null::<()>(), + len, + ); + ::std::alloc::Layout::for_value_raw(p) + } + } + #[inline] + pub fn fixed(&self) -> (&flexarray<[::std::os::raw::c_int; 0]>, usize) { + unsafe { + let (ptr, len) = (self as *const Self).to_raw_parts(); + (&*(ptr as *const flexarray<[::std::os::raw::c_int; 0]>), len) + } + } + #[inline] + pub fn fixed_mut(&mut self) -> (&mut flexarray<[::std::os::raw::c_int; 0]>, usize) { + unsafe { + let (ptr, len) = (self as *mut Self).to_raw_parts(); + (&mut *(ptr as *mut flexarray<[::std::os::raw::c_int; 0]>), len) + } + } +} +impl flexarray<[::std::os::raw::c_int; 0]> { + /// Convert a sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + pub unsafe fn flex_ref(&self, len: usize) -> &flexarray<[::std::os::raw::c_int]> { + Self::flex_ptr(self, len) + } + /// Convert a mutable sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ref_mut( + &mut self, + len: usize, + ) -> &mut flexarray<[::std::os::raw::c_int]> { + Self::flex_ptr_mut(self, len).assume_init() + } + /// Construct DST variant from a pointer and a size. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage is fully initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ptr<'unbounded>( + ptr: *const Self, + len: usize, + ) -> &'unbounded flexarray<[::std::os::raw::c_int]> { + &*::std::ptr::from_raw_parts(ptr as *const (), len) + } + /// Construct mutable DST variant from a pointer and a + /// size. The returned `&mut` reference is initialized + /// pointing to memory referenced by `ptr`, but there's + /// no requirement that that memory be initialized. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage has space for at least `len` elements. + #[inline] + pub unsafe fn flex_ptr_mut<'unbounded>( + ptr: *mut Self, + len: usize, + ) -> ::std::mem::MaybeUninit<&'unbounded mut flexarray<[::std::os::raw::c_int]>> { + let mut uninit = ::std::mem::MaybeUninit::< + &mut flexarray<[::std::os::raw::c_int]>, + >::uninit(); + (uninit.as_mut_ptr() as *mut *mut flexarray<[::std::os::raw::c_int]>) + .write(::std::ptr::from_raw_parts_mut(ptr as *mut (), len)); + uninit + } +} +#[repr(C)] +#[derive(Debug, Default)] +pub struct flexarray_zero { + pub count: ::std::os::raw::c_int, + pub data: FAM, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of flexarray_zero"][::std::mem::size_of::() - 4usize]; + ["Alignment of flexarray_zero"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: flexarray_zero::count", + ][::std::mem::offset_of!(flexarray_zero, count) - 0usize]; + [ + "Offset of field: flexarray_zero::data", + ][::std::mem::offset_of!(flexarray_zero, data) - 4usize]; +}; +impl flexarray_zero<[::std::os::raw::c_int]> { + pub fn layout(len: usize) -> ::std::alloc::Layout { + unsafe { + let p: *const Self = ::std::ptr::from_raw_parts( + ::std::ptr::null::<()>(), + len, + ); + ::std::alloc::Layout::for_value_raw(p) + } + } + #[inline] + pub fn fixed(&self) -> (&flexarray_zero<[::std::os::raw::c_int; 0]>, usize) { + unsafe { + let (ptr, len) = (self as *const Self).to_raw_parts(); + (&*(ptr as *const flexarray_zero<[::std::os::raw::c_int; 0]>), len) + } + } + #[inline] + pub fn fixed_mut( + &mut self, + ) -> (&mut flexarray_zero<[::std::os::raw::c_int; 0]>, usize) { + unsafe { + let (ptr, len) = (self as *mut Self).to_raw_parts(); + (&mut *(ptr as *mut flexarray_zero<[::std::os::raw::c_int; 0]>), len) + } + } +} +impl flexarray_zero<[::std::os::raw::c_int; 0]> { + /// Convert a sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + pub unsafe fn flex_ref( + &self, + len: usize, + ) -> &flexarray_zero<[::std::os::raw::c_int]> { + Self::flex_ptr(self, len) + } + /// Convert a mutable sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ref_mut( + &mut self, + len: usize, + ) -> &mut flexarray_zero<[::std::os::raw::c_int]> { + Self::flex_ptr_mut(self, len).assume_init() + } + /// Construct DST variant from a pointer and a size. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage is fully initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ptr<'unbounded>( + ptr: *const Self, + len: usize, + ) -> &'unbounded flexarray_zero<[::std::os::raw::c_int]> { + &*::std::ptr::from_raw_parts(ptr as *const (), len) + } + /// Construct mutable DST variant from a pointer and a + /// size. The returned `&mut` reference is initialized + /// pointing to memory referenced by `ptr`, but there's + /// no requirement that that memory be initialized. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage has space for at least `len` elements. + #[inline] + pub unsafe fn flex_ptr_mut<'unbounded>( + ptr: *mut Self, + len: usize, + ) -> ::std::mem::MaybeUninit< + &'unbounded mut flexarray_zero<[::std::os::raw::c_int]>, + > { + let mut uninit = ::std::mem::MaybeUninit::< + &mut flexarray_zero<[::std::os::raw::c_int]>, + >::uninit(); + (uninit.as_mut_ptr() as *mut *mut flexarray_zero<[::std::os::raw::c_int]>) + .write(::std::ptr::from_raw_parts_mut(ptr as *mut (), len)); + uninit + } +} +#[repr(C)] +#[derive(Debug)] +pub struct flexarray_template { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub count: ::std::os::raw::c_int, + pub data: FAM, +} +impl flexarray_template { + pub fn layout(len: usize) -> ::std::alloc::Layout { + unsafe { + let p: *const Self = ::std::ptr::from_raw_parts( + ::std::ptr::null::<()>(), + len, + ); + ::std::alloc::Layout::for_value_raw(p) + } + } + #[inline] + pub fn fixed(&self) -> (&flexarray_template, usize) { + unsafe { + let (ptr, len) = (self as *const Self).to_raw_parts(); + (&*(ptr as *const flexarray_template), len) + } + } + #[inline] + pub fn fixed_mut(&mut self) -> (&mut flexarray_template, usize) { + unsafe { + let (ptr, len) = (self as *mut Self).to_raw_parts(); + (&mut *(ptr as *mut flexarray_template), len) + } + } +} +impl flexarray_template { + /// Convert a sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + pub unsafe fn flex_ref(&self, len: usize) -> &flexarray_template { + Self::flex_ptr(self, len) + } + /// Convert a mutable sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ref_mut( + &mut self, + len: usize, + ) -> &mut flexarray_template { + Self::flex_ptr_mut(self, len).assume_init() + } + /// Construct DST variant from a pointer and a size. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage is fully initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ptr<'unbounded>( + ptr: *const Self, + len: usize, + ) -> &'unbounded flexarray_template { + &*::std::ptr::from_raw_parts(ptr as *const (), len) + } + /// Construct mutable DST variant from a pointer and a + /// size. The returned `&mut` reference is initialized + /// pointing to memory referenced by `ptr`, but there's + /// no requirement that that memory be initialized. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage has space for at least `len` elements. + #[inline] + pub unsafe fn flex_ptr_mut<'unbounded>( + ptr: *mut Self, + len: usize, + ) -> ::std::mem::MaybeUninit<&'unbounded mut flexarray_template> { + let mut uninit = ::std::mem::MaybeUninit::< + &mut flexarray_template, + >::uninit(); + (uninit.as_mut_ptr() as *mut *mut flexarray_template) + .write(::std::ptr::from_raw_parts_mut(ptr as *mut (), len)); + uninit + } +} +impl Default for flexarray_template { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct flexarray_ref { + pub things: *mut flexarray, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of flexarray_ref"][::std::mem::size_of::() - 8usize]; + ["Alignment of flexarray_ref"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: flexarray_ref::things", + ][::std::mem::offset_of!(flexarray_ref, things) - 0usize]; +}; +impl Default for flexarray_ref { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[repr(C)] +#[derive(Debug, Default)] +pub struct flexarray_bogus_zero_fam { + pub count: ::std::os::raw::c_int, + pub data1: __IncompleteArrayField<::std::os::raw::c_int>, + pub data2: FAM, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of flexarray_bogus_zero_fam", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of flexarray_bogus_zero_fam", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: flexarray_bogus_zero_fam::count", + ][::std::mem::offset_of!(flexarray_bogus_zero_fam, count) - 0usize]; + [ + "Offset of field: flexarray_bogus_zero_fam::data1", + ][::std::mem::offset_of!(flexarray_bogus_zero_fam, data1) - 4usize]; + [ + "Offset of field: flexarray_bogus_zero_fam::data2", + ][::std::mem::offset_of!(flexarray_bogus_zero_fam, data2) - 4usize]; +}; +impl flexarray_bogus_zero_fam<[::std::os::raw::c_char]> { + pub fn layout(len: usize) -> ::std::alloc::Layout { + unsafe { + let p: *const Self = ::std::ptr::from_raw_parts( + ::std::ptr::null::<()>(), + len, + ); + ::std::alloc::Layout::for_value_raw(p) + } + } + #[inline] + pub fn fixed( + &self, + ) -> (&flexarray_bogus_zero_fam<[::std::os::raw::c_char; 0]>, usize) { + unsafe { + let (ptr, len) = (self as *const Self).to_raw_parts(); + ( + &*(ptr as *const flexarray_bogus_zero_fam<[::std::os::raw::c_char; 0]>), + len, + ) + } + } + #[inline] + pub fn fixed_mut( + &mut self, + ) -> (&mut flexarray_bogus_zero_fam<[::std::os::raw::c_char; 0]>, usize) { + unsafe { + let (ptr, len) = (self as *mut Self).to_raw_parts(); + ( + &mut *(ptr + as *mut flexarray_bogus_zero_fam<[::std::os::raw::c_char; 0]>), + len, + ) + } + } +} +impl flexarray_bogus_zero_fam<[::std::os::raw::c_char; 0]> { + /// Convert a sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + pub unsafe fn flex_ref( + &self, + len: usize, + ) -> &flexarray_bogus_zero_fam<[::std::os::raw::c_char]> { + Self::flex_ptr(self, len) + } + /// Convert a mutable sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ref_mut( + &mut self, + len: usize, + ) -> &mut flexarray_bogus_zero_fam<[::std::os::raw::c_char]> { + Self::flex_ptr_mut(self, len).assume_init() + } + /// Construct DST variant from a pointer and a size. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage is fully initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ptr<'unbounded>( + ptr: *const Self, + len: usize, + ) -> &'unbounded flexarray_bogus_zero_fam<[::std::os::raw::c_char]> { + &*::std::ptr::from_raw_parts(ptr as *const (), len) + } + /// Construct mutable DST variant from a pointer and a + /// size. The returned `&mut` reference is initialized + /// pointing to memory referenced by `ptr`, but there's + /// no requirement that that memory be initialized. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage has space for at least `len` elements. + #[inline] + pub unsafe fn flex_ptr_mut<'unbounded>( + ptr: *mut Self, + len: usize, + ) -> ::std::mem::MaybeUninit< + &'unbounded mut flexarray_bogus_zero_fam<[::std::os::raw::c_char]>, + > { + let mut uninit = ::std::mem::MaybeUninit::< + &mut flexarray_bogus_zero_fam<[::std::os::raw::c_char]>, + >::uninit(); + (uninit.as_mut_ptr() + as *mut *mut flexarray_bogus_zero_fam<[::std::os::raw::c_char]>) + .write(::std::ptr::from_raw_parts_mut(ptr as *mut (), len)); + uninit + } +} +#[repr(C)] +#[repr(align(128))] +#[derive(Debug)] +pub struct flexarray_align { + pub count: ::std::os::raw::c_int, + pub data: FAM, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of flexarray_align"][::std::mem::size_of::() - 128usize]; + [ + "Alignment of flexarray_align", + ][::std::mem::align_of::() - 128usize]; + [ + "Offset of field: flexarray_align::count", + ][::std::mem::offset_of!(flexarray_align, count) - 0usize]; + [ + "Offset of field: flexarray_align::data", + ][::std::mem::offset_of!(flexarray_align, data) - 4usize]; +}; +impl flexarray_align<[::std::os::raw::c_int]> { + pub fn layout(len: usize) -> ::std::alloc::Layout { + unsafe { + let p: *const Self = ::std::ptr::from_raw_parts( + ::std::ptr::null::<()>(), + len, + ); + ::std::alloc::Layout::for_value_raw(p) + } + } + #[inline] + pub fn fixed(&self) -> (&flexarray_align<[::std::os::raw::c_int; 0]>, usize) { + unsafe { + let (ptr, len) = (self as *const Self).to_raw_parts(); + (&*(ptr as *const flexarray_align<[::std::os::raw::c_int; 0]>), len) + } + } + #[inline] + pub fn fixed_mut( + &mut self, + ) -> (&mut flexarray_align<[::std::os::raw::c_int; 0]>, usize) { + unsafe { + let (ptr, len) = (self as *mut Self).to_raw_parts(); + (&mut *(ptr as *mut flexarray_align<[::std::os::raw::c_int; 0]>), len) + } + } +} +impl flexarray_align<[::std::os::raw::c_int; 0]> { + /// Convert a sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + pub unsafe fn flex_ref( + &self, + len: usize, + ) -> &flexarray_align<[::std::os::raw::c_int]> { + Self::flex_ptr(self, len) + } + /// Convert a mutable sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ref_mut( + &mut self, + len: usize, + ) -> &mut flexarray_align<[::std::os::raw::c_int]> { + Self::flex_ptr_mut(self, len).assume_init() + } + /// Construct DST variant from a pointer and a size. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage is fully initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ptr<'unbounded>( + ptr: *const Self, + len: usize, + ) -> &'unbounded flexarray_align<[::std::os::raw::c_int]> { + &*::std::ptr::from_raw_parts(ptr as *const (), len) + } + /// Construct mutable DST variant from a pointer and a + /// size. The returned `&mut` reference is initialized + /// pointing to memory referenced by `ptr`, but there's + /// no requirement that that memory be initialized. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage has space for at least `len` elements. + #[inline] + pub unsafe fn flex_ptr_mut<'unbounded>( + ptr: *mut Self, + len: usize, + ) -> ::std::mem::MaybeUninit< + &'unbounded mut flexarray_align<[::std::os::raw::c_int]>, + > { + let mut uninit = ::std::mem::MaybeUninit::< + &mut flexarray_align<[::std::os::raw::c_int]>, + >::uninit(); + (uninit.as_mut_ptr() as *mut *mut flexarray_align<[::std::os::raw::c_int]>) + .write(::std::ptr::from_raw_parts_mut(ptr as *mut (), len)); + uninit + } +} +impl Default for flexarray_align<[::std::os::raw::c_int; 0]> { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} diff --git a/bindgen-tests/tests/expectations/tests/float16.rs b/bindgen-tests/tests/expectations/tests/float16.rs index b5471b1efa..2066b71801 100644 --- a/bindgen-tests/tests/expectations/tests/float16.rs +++ b/bindgen-tests/tests/expectations/tests/float16.rs @@ -2,7 +2,7 @@ #[derive(PartialEq, Copy, Clone, Hash, Debug, Default)] #[repr(transparent)] pub struct __BindgenFloat16(pub u16); -extern "C" { +unsafe extern "C" { pub static mut global: __BindgenFloat16; } #[repr(C)] @@ -10,51 +10,29 @@ extern "C" { pub struct Test__Float16 { pub f: __BindgenFloat16, } -#[test] -fn bindgen_test_layout_Test__Float16() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(Test__Float16)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(Test__Float16)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test__Float16), "::", stringify!(f)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test__Float16"][::std::mem::size_of::() - 2usize]; + ["Alignment of Test__Float16"][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: Test__Float16::f", + ][::std::mem::offset_of!(Test__Float16, f) - 0usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Test__Float16Ref { pub f: *mut __BindgenFloat16, } -#[test] -fn bindgen_test_layout_Test__Float16Ref() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Test__Float16Ref)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Test__Float16Ref)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test__Float16Ref), "::", stringify!(f)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test__Float16Ref"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of Test__Float16Ref", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: Test__Float16Ref::f", + ][::std::mem::offset_of!(Test__Float16Ref, f) - 0usize]; +}; impl Default for Test__Float16Ref { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/forward-declaration-autoptr.rs b/bindgen-tests/tests/expectations/tests/forward-declaration-autoptr.rs index 7c483638eb..b74b408841 100644 --- a/bindgen-tests/tests/expectations/tests/forward-declaration-autoptr.rs +++ b/bindgen-tests/tests/expectations/tests/forward-declaration-autoptr.rs @@ -7,8 +7,8 @@ pub struct Foo { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RefPtr { - pub m_inner: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub m_inner: *mut T, } impl Default for RefPtr { fn default() -> Self { @@ -24,26 +24,12 @@ impl Default for RefPtr { pub struct Bar { pub m_member: RefPtr, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m_member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(m_member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::m_member"][::std::mem::offset_of!(Bar, m_member) - 0usize]; +}; impl Default for Bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -53,16 +39,12 @@ impl Default for Bar { } } } -#[test] -fn __bindgen_test_layout_RefPtr_open0_Foo_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!("Size of template specialization: ", stringify!(RefPtr < Foo >)), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!("Alignment of template specialization: ", stringify!(RefPtr < Foo >)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: RefPtr_open0_Foo_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: RefPtr_open0_Foo_close0", + ][::std::mem::align_of::>() - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/forward-inherit-struct-with-fields.rs b/bindgen-tests/tests/expectations/tests/forward-inherit-struct-with-fields.rs index 0e5bcd969f..069c76fead 100644 --- a/bindgen-tests/tests/expectations/tests/forward-inherit-struct-with-fields.rs +++ b/bindgen-tests/tests/expectations/tests/forward-inherit-struct-with-fields.rs @@ -2,9 +2,9 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct js_RootedBase { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub foo: *mut T, pub next: *mut Rooted, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for js_RootedBase { fn default() -> Self { @@ -18,8 +18,8 @@ impl Default for js_RootedBase { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Rooted { - pub _base: js_RootedBase, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub _base: js_RootedBase, } impl Default for Rooted { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/forward_declared_complex_types.rs b/bindgen-tests/tests/expectations/tests/forward_declared_complex_types.rs index 5a8d5aebaf..79554d58e4 100644 --- a/bindgen-tests/tests/expectations/tests/forward_declared_complex_types.rs +++ b/bindgen-tests/tests/expectations/tests/forward_declared_complex_types.rs @@ -4,19 +4,11 @@ pub struct Foo_empty { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo_empty() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo_empty)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo_empty)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo_empty"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo_empty"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Foo { @@ -27,26 +19,12 @@ pub struct Foo { pub struct Bar { pub f: *mut Foo, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(f)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::f"][::std::mem::offset_of!(Bar, f) - 0usize]; +}; impl Default for Bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -56,7 +34,7 @@ impl Default for Bar { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z10baz_structP3Foo"] pub fn baz_struct(f: *mut Foo); } @@ -65,7 +43,7 @@ extern "C" { pub struct Union { _unused: [u8; 0], } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z9baz_unionP5Union"] pub fn baz_union(u: *mut Union); } @@ -74,7 +52,7 @@ extern "C" { pub struct Quux { _unused: [u8; 0], } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z9baz_classP4Quux"] pub fn baz_class(q: *mut Quux); } diff --git a/bindgen-tests/tests/expectations/tests/forward_declared_complex_types_1_0.rs b/bindgen-tests/tests/expectations/tests/forward_declared_complex_types_1_0.rs deleted file mode 100644 index e03884bfe6..0000000000 --- a/bindgen-tests/tests/expectations/tests/forward_declared_complex_types_1_0.rs +++ /dev/null @@ -1,105 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Debug, Default, Copy)] -pub struct Foo_empty { - pub _address: u8, -} -#[test] -fn bindgen_test_layout_Foo_empty() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo_empty)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo_empty)), - ); -} -impl Clone for Foo_empty { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Copy)] -pub struct Foo { - _unused: [u8; 0], -} -impl Clone for Foo { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Copy)] -pub struct Bar { - pub f: *mut Foo, -} -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(f)), - ); -} -impl Clone for Bar { - fn clone(&self) -> Self { - *self - } -} -impl Default for Bar { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -extern "C" { - #[link_name = "\u{1}_Z10baz_structP3Foo"] - pub fn baz_struct(f: *mut Foo); -} -#[repr(C)] -#[derive(Debug, Copy)] -pub struct Union { - _unused: [u8; 0], -} -impl Clone for Union { - fn clone(&self) -> Self { - *self - } -} -extern "C" { - #[link_name = "\u{1}_Z9baz_unionP5Union"] - pub fn baz_union(u: *mut Union); -} -#[repr(C)] -#[derive(Debug, Copy)] -pub struct Quux { - _unused: [u8; 0], -} -impl Clone for Quux { - fn clone(&self) -> Self { - *self - } -} -extern "C" { - #[link_name = "\u{1}_Z9baz_classP4Quux"] - pub fn baz_class(q: *mut Quux); -} diff --git a/bindgen-tests/tests/expectations/tests/forward_declared_struct.rs b/bindgen-tests/tests/expectations/tests/forward_declared_struct.rs index 8960ff11b3..1f6dfd0f58 100644 --- a/bindgen-tests/tests/expectations/tests/forward_declared_struct.rs +++ b/bindgen-tests/tests/expectations/tests/forward_declared_struct.rs @@ -4,40 +4,20 @@ pub struct a { pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_a() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(a))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(a), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of a"][::std::mem::size_of::() - 4usize]; + ["Alignment of a"][::std::mem::align_of::() - 4usize]; + ["Offset of field: a::b"][::std::mem::offset_of!(a, b) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct c { pub d: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_c() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(c))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(c)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(c), "::", stringify!(d)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of c"][::std::mem::size_of::() - 4usize]; + ["Alignment of c"][::std::mem::align_of::() - 4usize]; + ["Offset of field: c::d"][::std::mem::offset_of!(c, d) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/func_ptr.rs b/bindgen-tests/tests/expectations/tests/func_ptr.rs index 4e9c5b131d..b91bdba872 100644 --- a/bindgen-tests/tests/expectations/tests/func_ptr.rs +++ b/bindgen-tests/tests/expectations/tests/func_ptr.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub static mut foo: ::std::option::Option< unsafe extern "C" fn( x: ::std::os::raw::c_int, diff --git a/bindgen-tests/tests/expectations/tests/func_ptr_in_struct.rs b/bindgen-tests/tests/expectations/tests/func_ptr_in_struct.rs index d0ba38ad3a..308bb069e0 100644 --- a/bindgen-tests/tests/expectations/tests/func_ptr_in_struct.rs +++ b/bindgen-tests/tests/expectations/tests/func_ptr_in_struct.rs @@ -11,23 +11,9 @@ pub struct Foo { unsafe extern "C" fn(x: ::std::os::raw::c_int, y: ::std::os::raw::c_int) -> baz, >, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Foo::bar"][::std::mem::offset_of!(Foo, bar) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/func_ptr_return_type.rs b/bindgen-tests/tests/expectations/tests/func_ptr_return_type.rs index c1c890249f..504eefdfb1 100644 --- a/bindgen-tests/tests/expectations/tests/func_ptr_return_type.rs +++ b/bindgen-tests/tests/expectations/tests/func_ptr_return_type.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn func() -> ::std::option::Option< unsafe extern "C" fn( arg1: ::std::os::raw::c_int, diff --git a/bindgen-tests/tests/expectations/tests/func_return_must_use.rs b/bindgen-tests/tests/expectations/tests/func_return_must_use.rs index e12c433c22..904c71cbe3 100644 --- a/bindgen-tests/tests/expectations/tests/func_return_must_use.rs +++ b/bindgen-tests/tests/expectations/tests/func_return_must_use.rs @@ -1,6 +1,6 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] pub type MustUseInt = ::std::os::raw::c_int; -extern "C" { +unsafe extern "C" { #[must_use] pub fn return_int() -> MustUseInt; } @@ -10,17 +10,17 @@ extern "C" { pub struct MustUseStruct { _unused: [u8; 0], } -extern "C" { +unsafe extern "C" { #[must_use] pub fn return_struct() -> MustUseStruct; } ///

pub type AnnotatedInt = ::std::os::raw::c_int; -extern "C" { +unsafe extern "C" { #[must_use] pub fn return_annotated_int() -> AnnotatedInt; } -extern "C" { +unsafe extern "C" { pub fn return_plain_int() -> ::std::os::raw::c_int; } ///
@@ -28,45 +28,29 @@ extern "C" { #[derive(Debug, Default, Copy, Clone)] #[must_use] pub struct AnnotatedStruct {} -#[test] -fn bindgen_test_layout_AnnotatedStruct() { - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(AnnotatedStruct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(AnnotatedStruct)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AnnotatedStruct"][::std::mem::size_of::() - 0usize]; + ["Alignment of AnnotatedStruct"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[must_use] pub fn return_annotated_struct() -> AnnotatedStruct; } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct PlainStruct {} -#[test] -fn bindgen_test_layout_PlainStruct() { - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(PlainStruct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(PlainStruct)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of PlainStruct"][::std::mem::size_of::() - 0usize]; + ["Alignment of PlainStruct"][::std::mem::align_of::() - 1usize]; +}; ///
pub type TypedefPlainStruct = PlainStruct; -extern "C" { +unsafe extern "C" { pub fn return_plain_struct() -> PlainStruct; } -extern "C" { +unsafe extern "C" { #[must_use] pub fn return_typedef_struct() -> TypedefPlainStruct; } diff --git a/bindgen-tests/tests/expectations/tests/func_with_array_arg.rs b/bindgen-tests/tests/expectations/tests/func_with_array_arg.rs index e41cb2ce44..20bdc4ac27 100644 --- a/bindgen-tests/tests/expectations/tests/func_with_array_arg.rs +++ b/bindgen-tests/tests/expectations/tests/func_with_array_arg.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn f(x: *mut ::std::os::raw::c_int); } diff --git a/bindgen-tests/tests/expectations/tests/func_with_func_ptr_arg.rs b/bindgen-tests/tests/expectations/tests/func_with_func_ptr_arg.rs index af8a3fc68c..56cf40fb59 100644 --- a/bindgen-tests/tests/expectations/tests/func_with_func_ptr_arg.rs +++ b/bindgen-tests/tests/expectations/tests/func_with_func_ptr_arg.rs @@ -1,8 +1,8 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(bar: ::std::option::Option); } -extern "C" { +unsafe extern "C" { pub fn bar( one: ::std::option::Option< unsafe extern "C" fn(a: ::std::os::raw::c_int, b: ::std::os::raw::c_int), diff --git a/bindgen-tests/tests/expectations/tests/gen-constructors-neg.rs b/bindgen-tests/tests/expectations/tests/gen-constructors-neg.rs index d51ccfa80c..551dff82cf 100644 --- a/bindgen-tests/tests/expectations/tests/gen-constructors-neg.rs +++ b/bindgen-tests/tests/expectations/tests/gen-constructors-neg.rs @@ -4,16 +4,8 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/gen-constructors.rs b/bindgen-tests/tests/expectations/tests/gen-constructors.rs index b46ee61a16..80e6a25d70 100644 --- a/bindgen-tests/tests/expectations/tests/gen-constructors.rs +++ b/bindgen-tests/tests/expectations/tests/gen-constructors.rs @@ -4,20 +4,12 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3FooC1Ei"] pub fn Foo_Foo(this: *mut Foo, a: ::std::os::raw::c_int); } diff --git a/bindgen-tests/tests/expectations/tests/gen-destructors-neg.rs b/bindgen-tests/tests/expectations/tests/gen-destructors-neg.rs index 67f00f79ee..77b6a07bb1 100644 --- a/bindgen-tests/tests/expectations/tests/gen-destructors-neg.rs +++ b/bindgen-tests/tests/expectations/tests/gen-destructors-neg.rs @@ -4,23 +4,9 @@ pub struct Foo { pub bar: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo::bar"][::std::mem::offset_of!(Foo, bar) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/gen-destructors.rs b/bindgen-tests/tests/expectations/tests/gen-destructors.rs index 47adf19cce..c860c9985f 100644 --- a/bindgen-tests/tests/expectations/tests/gen-destructors.rs +++ b/bindgen-tests/tests/expectations/tests/gen-destructors.rs @@ -4,27 +4,13 @@ pub struct Foo { pub bar: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(bar)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo::bar"][::std::mem::offset_of!(Foo, bar) - 0usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3FooD1Ev"] pub fn Foo_Foo_destructor(this: *mut Foo); } diff --git a/bindgen-tests/tests/expectations/tests/generate-inline.rs b/bindgen-tests/tests/expectations/tests/generate-inline.rs index ce34c1ec17..c100f3936c 100644 --- a/bindgen-tests/tests/expectations/tests/generate-inline.rs +++ b/bindgen-tests/tests/expectations/tests/generate-inline.rs @@ -4,20 +4,12 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo3barEv"] pub fn Foo_bar() -> ::std::os::raw::c_int; } @@ -27,7 +19,7 @@ impl Foo { Foo_bar() } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z3foov"] pub fn foo() -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/i128.rs b/bindgen-tests/tests/expectations/tests/i128.rs index 0c7c5e0223..87459b5e75 100644 --- a/bindgen-tests/tests/expectations/tests/i128.rs +++ b/bindgen-tests/tests/expectations/tests/i128.rs @@ -10,24 +10,16 @@ pub struct foo { fn bindgen_test_layout_foo() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 32usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(foo)), - ); + assert_eq!(::std::mem::size_of::(), 32usize, "Size of foo"); + assert_eq!(::std::mem::align_of::(), 16usize, "Alignment of foo"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).my_signed) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(my_signed)), + "Offset of field: foo::my_signed", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).my_unsigned) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(my_unsigned)), + "Offset of field: foo::my_unsigned", ); } diff --git a/bindgen-tests/tests/expectations/tests/incomplete-array-padding.rs b/bindgen-tests/tests/expectations/tests/incomplete-array-padding.rs index c8038e1f40..6e9f6e7753 100644 --- a/bindgen-tests/tests/expectations/tests/incomplete-array-padding.rs +++ b/bindgen-tests/tests/expectations/tests/incomplete-array-padding.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Default)] @@ -120,26 +182,12 @@ pub struct foo { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub b: __IncompleteArrayField<*mut ::std::os::raw::c_void>, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: foo::b"][::std::mem::offset_of!(foo, b) - 8usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -162,6 +210,30 @@ impl foo { } } #[inline] + pub unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_char { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_char) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( a: ::std::os::raw::c_char, ) -> __BindgenBitfieldUnit<[u8; 1usize]> { diff --git a/bindgen-tests/tests/expectations/tests/infinite-macro.rs b/bindgen-tests/tests/expectations/tests/infinite-macro.rs index 455a7ae5ed..f19879fb17 100644 --- a/bindgen-tests/tests/expectations/tests/infinite-macro.rs +++ b/bindgen-tests/tests/expectations/tests/infinite-macro.rs @@ -1,3 +1,3 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -pub const INFINITY: f64 = ::std::f64::INFINITY; -pub const NAN: f64 = ::std::f64::NAN; +pub const INFINITY: f64 = f64::INFINITY; +pub const NAN: f64 = f64::NAN; diff --git a/bindgen-tests/tests/expectations/tests/inherit-from-template-instantiation-with-vtable.rs b/bindgen-tests/tests/expectations/tests/inherit-from-template-instantiation-with-vtable.rs index 08f186d92b..59e35f7b6c 100644 --- a/bindgen-tests/tests/expectations/tests/inherit-from-template-instantiation-with-vtable.rs +++ b/bindgen-tests/tests/expectations/tests/inherit-from-template-instantiation-with-vtable.rs @@ -5,9 +5,9 @@ pub struct BaseWithVtable__bindgen_vtable {} #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct BaseWithVtable { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub vtable_: *const BaseWithVtable__bindgen_vtable, pub t: T, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for BaseWithVtable { fn default() -> Self { @@ -24,19 +24,15 @@ impl Default for BaseWithVtable { pub struct DerivedWithNoVirtualMethods { pub _base: BaseWithVtable<*mut ::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_DerivedWithNoVirtualMethods() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(DerivedWithNoVirtualMethods)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(DerivedWithNoVirtualMethods)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of DerivedWithNoVirtualMethods", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of DerivedWithNoVirtualMethods", + ][::std::mem::align_of::() - 8usize]; +}; impl Default for DerivedWithNoVirtualMethods { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -52,19 +48,15 @@ impl Default for DerivedWithNoVirtualMethods { pub struct DerivedWithVirtualMethods { pub _base: BaseWithVtable<*mut ::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_DerivedWithVirtualMethods() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(DerivedWithVirtualMethods)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(DerivedWithVirtualMethods)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of DerivedWithVirtualMethods", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of DerivedWithVirtualMethods", + ][::std::mem::align_of::() - 8usize]; +}; impl Default for DerivedWithVirtualMethods { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -78,8 +70,8 @@ impl Default for DerivedWithVirtualMethods { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct BaseWithoutVtable { - pub u: U, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub u: U, } impl Default for BaseWithoutVtable { fn default() -> Self { @@ -99,19 +91,13 @@ pub struct DerivedWithVtable { pub vtable_: *const DerivedWithVtable__bindgen_vtable, pub _base: BaseWithoutVtable<*mut ::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_DerivedWithVtable() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(DerivedWithVtable)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(DerivedWithVtable)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of DerivedWithVtable"][::std::mem::size_of::() - 16usize]; + [ + "Alignment of DerivedWithVtable", + ][::std::mem::align_of::() - 8usize]; +}; impl Default for DerivedWithVtable { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -127,19 +113,15 @@ impl Default for DerivedWithVtable { pub struct DerivedWithoutVtable { pub _base: BaseWithoutVtable<*mut ::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_DerivedWithoutVtable() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(DerivedWithoutVtable)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(DerivedWithoutVtable)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of DerivedWithoutVtable", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of DerivedWithoutVtable", + ][::std::mem::align_of::() - 8usize]; +}; impl Default for DerivedWithoutVtable { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -149,79 +131,39 @@ impl Default for DerivedWithoutVtable { } } } -#[test] -fn __bindgen_test_layout_BaseWithVtable_open0_ptr_char_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 16usize, - concat!( - "Size of template specialization: ", - stringify!(BaseWithVtable < * mut ::std::os::raw::c_char >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(BaseWithVtable < * mut ::std::os::raw::c_char >), - ), - ); -} -#[test] -fn __bindgen_test_layout_BaseWithVtable_open0_ptr_char_close0_instantiation_1() { - assert_eq!( - ::std::mem::size_of::>(), - 16usize, - concat!( - "Size of template specialization: ", - stringify!(BaseWithVtable < * mut ::std::os::raw::c_char >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(BaseWithVtable < * mut ::std::os::raw::c_char >), - ), - ); -} -#[test] -fn __bindgen_test_layout_BaseWithoutVtable_open0_ptr_char_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(BaseWithoutVtable < * mut ::std::os::raw::c_char >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(BaseWithoutVtable < * mut ::std::os::raw::c_char >), - ), - ); -} -#[test] -fn __bindgen_test_layout_BaseWithoutVtable_open0_ptr_char_close0_instantiation_1() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(BaseWithoutVtable < * mut ::std::os::raw::c_char >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(BaseWithoutVtable < * mut ::std::os::raw::c_char >), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: BaseWithVtable_open0_ptr_char_close0", + ][::std::mem::size_of::>() - 16usize]; + [ + "Align of template specialization: BaseWithVtable_open0_ptr_char_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: BaseWithVtable_open0_ptr_char_close0", + ][::std::mem::size_of::>() - 16usize]; + [ + "Align of template specialization: BaseWithVtable_open0_ptr_char_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: BaseWithoutVtable_open0_ptr_char_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: BaseWithoutVtable_open0_ptr_char_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: BaseWithoutVtable_open0_ptr_char_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: BaseWithoutVtable_open0_ptr_char_close0", + ][::std::mem::align_of::>() - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/inherit_multiple_interfaces.rs b/bindgen-tests/tests/expectations/tests/inherit_multiple_interfaces.rs index 76b2e3bd09..da9e519156 100644 --- a/bindgen-tests/tests/expectations/tests/inherit_multiple_interfaces.rs +++ b/bindgen-tests/tests/expectations/tests/inherit_multiple_interfaces.rs @@ -7,22 +7,12 @@ pub struct A { pub vtable_: *const A__bindgen_vtable, pub member: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit
= ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 16usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 16usize]; + ["Alignment of A"][::std::mem::align_of::() - 8usize]; + ["Offset of field: A::member"][::std::mem::offset_of!(A, member) - 8usize]; +}; impl Default for A { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -40,22 +30,12 @@ pub struct B { pub vtable_: *const B__bindgen_vtable, pub member2: *mut ::std::os::raw::c_void, } -#[test] -fn bindgen_test_layout_B() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 16usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(B)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member2) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(B), "::", stringify!(member2)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of B"][::std::mem::size_of::() - 16usize]; + ["Alignment of B"][::std::mem::align_of::() - 8usize]; + ["Offset of field: B::member2"][::std::mem::offset_of!(B, member2) - 8usize]; +}; impl Default for B { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -72,22 +52,12 @@ pub struct C { pub _base_1: B, pub member3: f32, } -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 40usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member3) as usize - ptr as usize }, - 32usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(member3)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 40usize]; + ["Alignment of C"][::std::mem::align_of::() - 8usize]; + ["Offset of field: C::member3"][::std::mem::offset_of!(C, member3) - 32usize]; +}; impl Default for C { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/inherit_named.rs b/bindgen-tests/tests/expectations/tests/inherit_named.rs index 4b3bbd7d63..a371249ab0 100644 --- a/bindgen-tests/tests/expectations/tests/inherit_named.rs +++ b/bindgen-tests/tests/expectations/tests/inherit_named.rs @@ -7,8 +7,8 @@ pub struct Wohoo { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Weeee { - pub _base: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub _base: T, } impl Default for Weeee { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/inherit_typedef.rs b/bindgen-tests/tests/expectations/tests/inherit_typedef.rs index 1d48635962..92320f45ef 100644 --- a/bindgen-tests/tests/expectations/tests/inherit_typedef.rs +++ b/bindgen-tests/tests/expectations/tests/inherit_typedef.rs @@ -4,35 +4,19 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; pub type TypedefedFoo = Foo; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Bar { pub _address: u8, } -#[test] -fn bindgen_test_layout_Bar() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/inline_namespace.rs b/bindgen-tests/tests/expectations/tests/inline_namespace.rs index 124542ba75..df05ab7b9d 100644 --- a/bindgen-tests/tests/expectations/tests/inline_namespace.rs +++ b/bindgen-tests/tests/expectations/tests/inline_namespace.rs @@ -13,24 +13,10 @@ pub mod root { pub struct Bar { pub baz: root::foo::Ty, } - #[test] - fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Bar::baz"][::std::mem::offset_of!(Bar, baz) - 0usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/inline_namespace_conservative.rs b/bindgen-tests/tests/expectations/tests/inline_namespace_conservative.rs index 957d7e880a..6941e74adb 100644 --- a/bindgen-tests/tests/expectations/tests/inline_namespace_conservative.rs +++ b/bindgen-tests/tests/expectations/tests/inline_namespace_conservative.rs @@ -18,24 +18,10 @@ pub mod root { pub struct Bar { pub baz: root::foo::bar::Ty, } - #[test] - fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Bar::baz"][::std::mem::offset_of!(Bar, baz) - 0usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/inline_namespace_macro.rs b/bindgen-tests/tests/expectations/tests/inline_namespace_macro.rs new file mode 100644 index 0000000000..99ca607d2f --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/inline_namespace_macro.rs @@ -0,0 +1,20 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub mod root { + #[allow(unused_imports)] + use self::super::root; + pub mod repro { + #[allow(unused_imports)] + use self::super::super::root; + #[repr(C)] + #[derive(Debug, Default, Copy, Clone)] + pub struct duration { + pub _address: u8, + } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of duration"][::std::mem::size_of::() - 1usize]; + ["Alignment of duration"][::std::mem::align_of::() - 1usize]; + }; + } +} diff --git a/bindgen-tests/tests/expectations/tests/inline_namespace_no_ns_enabled.rs b/bindgen-tests/tests/expectations/tests/inline_namespace_no_ns_enabled.rs index bc3a95d2a5..66359bd51b 100644 --- a/bindgen-tests/tests/expectations/tests/inline_namespace_no_ns_enabled.rs +++ b/bindgen-tests/tests/expectations/tests/inline_namespace_no_ns_enabled.rs @@ -2,10 +2,10 @@ #[repr(C)] #[derive(Debug)] pub struct std_basic_string { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub hider: std_basic_string_Alloc_hider, pub length: ::std::os::raw::c_ulong, pub __bindgen_anon_1: std_basic_string__bindgen_ty_1, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } #[repr(C)] #[derive(Debug, Copy, Clone)] @@ -24,8 +24,8 @@ impl Default for std_basic_string_Alloc_hider { #[repr(C)] #[derive(Debug)] pub struct std_basic_string__bindgen_ty_1 { - pub inline_storage: [CharT; 4usize], pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub inline_storage: [CharT; 4usize], } impl Default for std_basic_string__bindgen_ty_1 { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/inner-typedef-gh422.rs b/bindgen-tests/tests/expectations/tests/inner-typedef-gh422.rs index 0cc6880b44..16b1eb48ea 100644 --- a/bindgen-tests/tests/expectations/tests/inner-typedef-gh422.rs +++ b/bindgen-tests/tests/expectations/tests/inner-typedef-gh422.rs @@ -7,8 +7,8 @@ pub struct Foo { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Foo_InnerType { - pub t: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, } impl Default for Foo_InnerType { fn default() -> Self { @@ -20,7 +20,7 @@ impl Default for Foo_InnerType { } } pub type Bar = InnerType; -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z4funcv"] pub fn func() -> Bar; } diff --git a/bindgen-tests/tests/expectations/tests/inner_const.rs b/bindgen-tests/tests/expectations/tests/inner_const.rs index 6afa16bbac..ad8af7ce35 100644 --- a/bindgen-tests/tests/expectations/tests/inner_const.rs +++ b/bindgen-tests/tests/expectations/tests/inner_const.rs @@ -4,31 +4,17 @@ pub struct Foo { pub bar: ::std::os::raw::c_int, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo3BOOE"] pub static mut Foo_BOO: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo8whateverE"] pub static mut Foo_whatever: Foo; } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo::bar"][::std::mem::offset_of!(Foo, bar) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/inner_template_self.rs b/bindgen-tests/tests/expectations/tests/inner_template_self.rs index ecfe079d66..c8f9799be6 100644 --- a/bindgen-tests/tests/expectations/tests/inner_template_self.rs +++ b/bindgen-tests/tests/expectations/tests/inner_template_self.rs @@ -19,26 +19,14 @@ impl Default for LinkedList { pub struct InstantiateIt { pub m_list: LinkedList, } -#[test] -fn bindgen_test_layout_InstantiateIt() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(InstantiateIt)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(InstantiateIt)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m_list) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(InstantiateIt), "::", stringify!(m_list)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of InstantiateIt"][::std::mem::size_of::() - 16usize]; + ["Alignment of InstantiateIt"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: InstantiateIt::m_list", + ][::std::mem::offset_of!(InstantiateIt, m_list) - 0usize]; +}; impl Default for InstantiateIt { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -48,16 +36,12 @@ impl Default for InstantiateIt { } } } -#[test] -fn __bindgen_test_layout_LinkedList_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of template specialization: ", stringify!(LinkedList)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of template specialization: ", stringify!(LinkedList)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: LinkedList_open0_int_close0", + ][::std::mem::size_of::() - 16usize]; + [ + "Align of template specialization: LinkedList_open0_int_close0", + ][::std::mem::align_of::() - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-1034.rs b/bindgen-tests/tests/expectations/tests/issue-1034.rs index 7848090fba..1034520c48 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1034.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1034.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -89,19 +151,11 @@ pub struct S2 { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, } -#[test] -fn bindgen_test_layout_S2() { - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(S2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(S2)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of S2"][::std::mem::size_of::() - 2usize]; + ["Alignment of S2"][::std::mem::align_of::() - 1usize]; +}; impl S2 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 2usize]> { diff --git a/bindgen-tests/tests/expectations/tests/issue-1076-unnamed-bitfield-alignment.rs b/bindgen-tests/tests/expectations/tests/issue-1076-unnamed-bitfield-alignment.rs index 89c09cc62f..3d14c81a77 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1076-unnamed-bitfield-alignment.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1076-unnamed-bitfield-alignment.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -89,19 +151,11 @@ pub struct S1 { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, } -#[test] -fn bindgen_test_layout_S1() { - assert_eq!( - ::std::mem::size_of::(), - 3usize, - concat!("Size of: ", stringify!(S1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(S1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of S1"][::std::mem::size_of::() - 3usize]; + ["Alignment of S1"][::std::mem::align_of::() - 1usize]; +}; impl S1 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 3usize]> { diff --git a/bindgen-tests/tests/expectations/tests/issue-1113-template-references.rs b/bindgen-tests/tests/expectations/tests/issue-1113-template-references.rs index d42621beaf..c0e76d8047 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1113-template-references.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1113-template-references.rs @@ -2,10 +2,10 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Entry { - pub _base: K, - pub mData: V, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub _base: K, + pub mData: V, } impl Default for Entry { fn default() -> Self { @@ -25,10 +25,10 @@ pub type nsBaseHashtable_EntryType = Entry; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsBaseHashtable_EntryPtr { - pub mEntry: *mut nsBaseHashtable_EntryType, - pub mExistingEntry: bool, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub mEntry: *mut nsBaseHashtable_EntryType, + pub mExistingEntry: bool, } impl Default for nsBaseHashtable_EntryPtr { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/issue-1118-using-forward-decl.rs b/bindgen-tests/tests/expectations/tests/issue-1118-using-forward-decl.rs index 2c60226142..7df1cdb741 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1118-using-forward-decl.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1118-using-forward-decl.rs @@ -5,26 +5,14 @@ pub type c = nsTArray; pub struct nsTArray_base { pub d: *mut ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_nsTArray_base() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsTArray_base)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsTArray_base)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsTArray_base), "::", stringify!(d)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of nsTArray_base"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsTArray_base"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: nsTArray_base::d", + ][::std::mem::offset_of!(nsTArray_base, d) - 0usize]; +}; impl Default for nsTArray_base { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -53,26 +41,14 @@ impl Default for nsTArray { pub struct nsIContent { pub foo: nsTArray, } -#[test] -fn bindgen_test_layout_nsIContent() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsIContent)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsIContent)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsIContent), "::", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of nsIContent"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsIContent"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: nsIContent::foo", + ][::std::mem::offset_of!(nsIContent, foo) - 0usize]; +}; impl Default for nsIContent { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -82,33 +58,25 @@ impl Default for nsIContent { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z35Gecko_GetAnonymousContentForElementv"] pub fn Gecko_GetAnonymousContentForElement() -> *mut nsTArray; } -#[test] -fn __bindgen_test_layout_nsTArray_open0_ptr_nsIContent_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of template specialization: ", stringify!(nsTArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of template specialization: ", stringify!(nsTArray)), - ); -} -#[test] -fn __bindgen_test_layout_nsTArray_open0_ptr_nsIContent_close0_instantiation_1() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of template specialization: ", stringify!(nsTArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of template specialization: ", stringify!(nsTArray)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: nsTArray_open0_ptr_nsIContent_close0", + ][::std::mem::size_of::() - 8usize]; + [ + "Align of template specialization: nsTArray_open0_ptr_nsIContent_close0", + ][::std::mem::align_of::() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: nsTArray_open0_ptr_nsIContent_close0", + ][::std::mem::size_of::() - 8usize]; + [ + "Align of template specialization: nsTArray_open0_ptr_nsIContent_close0", + ][::std::mem::align_of::() - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-1197-pure-virtual-stuff.rs b/bindgen-tests/tests/expectations/tests/issue-1197-pure-virtual-stuff.rs index 45ffb3d8b3..10c769c38c 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1197-pure-virtual-stuff.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1197-pure-virtual-stuff.rs @@ -6,19 +6,11 @@ pub struct Foo__bindgen_vtable(::std::os::raw::c_void); pub struct Foo { pub vtable_: *const Foo__bindgen_vtable, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 8usize]; +}; impl Default for Foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/issue-1198-alias-rust-bitfield-enum.rs b/bindgen-tests/tests/expectations/tests/issue-1198-alias-rust-bitfield-enum.rs index 7bbcb0d50b..5aaff691b4 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1198-alias-rust-bitfield-enum.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1198-alias-rust-bitfield-enum.rs @@ -1,11 +1,7 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] impl MyDupeEnum { pub const A: MyDupeEnum = MyDupeEnum(0); -} -impl MyDupeEnum { pub const A_alias: MyDupeEnum = MyDupeEnum(0); -} -impl MyDupeEnum { pub const B: MyDupeEnum = MyDupeEnum(1); } impl ::std::ops::BitOr for MyDupeEnum { @@ -39,11 +35,7 @@ impl ::std::ops::BitAndAssign for MyDupeEnum { pub struct MyDupeEnum(pub ::std::os::raw::c_uint); impl MyOtherDupeEnum { pub const C: MyOtherDupeEnum = MyOtherDupeEnum(0); -} -impl MyOtherDupeEnum { pub const C_alias: MyOtherDupeEnum = MyOtherDupeEnum(0); -} -impl MyOtherDupeEnum { pub const D: MyOtherDupeEnum = MyOtherDupeEnum(1); } impl ::std::ops::BitOr for MyOtherDupeEnum { diff --git a/bindgen-tests/tests/expectations/tests/issue-1216-variadic-member.rs b/bindgen-tests/tests/expectations/tests/issue-1216-variadic-member.rs index f7bbeba92b..7c562437e4 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1216-variadic-member.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1216-variadic-member.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn f(a: ::std::os::raw::c_int, ...); } #[repr(C)] @@ -14,23 +14,9 @@ pub struct Foo { ), >, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(f)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Foo::f"][::std::mem::offset_of!(Foo, f) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-1281.rs b/bindgen-tests/tests/expectations/tests/issue-1281.rs index 8e0096c904..03c80d21fb 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1281.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1281.rs @@ -9,69 +9,27 @@ pub struct bar { pub struct foo { pub foo: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(foo)), - ); -} -#[test] -fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(u)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::foo"][::std::mem::offset_of!(foo, foo) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: bar::u"][::std::mem::offset_of!(bar, u) - 0usize]; +}; pub type bar_t = bar; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct baz { pub f: foo, } -#[test] -fn bindgen_test_layout_baz() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(baz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(baz), "::", stringify!(f)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of baz"][::std::mem::size_of::() - 4usize]; + ["Alignment of baz"][::std::mem::align_of::() - 4usize]; + ["Offset of field: baz::f"][::std::mem::offset_of!(baz, f) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-1285.rs b/bindgen-tests/tests/expectations/tests/issue-1285.rs index 506b6a8819..6520163259 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1285.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1285.rs @@ -10,31 +10,19 @@ pub union foo__bindgen_ty_1 { pub a: ::std::os::raw::c_uint, pub b: ::std::os::raw::c_ushort, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 0usize]; +}; impl Default for foo__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -44,26 +32,12 @@ impl Default for foo__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/issue-1291.rs b/bindgen-tests/tests/expectations/tests/issue-1291.rs index 1a9e14518b..190e899d7f 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1291.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1291.rs @@ -23,89 +23,81 @@ pub struct RTCRay { fn bindgen_test_layout_RTCRay() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 96usize, - concat!("Size of: ", stringify!(RTCRay)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(RTCRay)), - ); + assert_eq!(::std::mem::size_of::(), 96usize, "Size of RTCRay"); + assert_eq!(::std::mem::align_of::(), 16usize, "Alignment of RTCRay"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).org) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(org)), + "Offset of field: RTCRay::org", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).align0) as usize - ptr as usize }, 12usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(align0)), + "Offset of field: RTCRay::align0", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dir) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(dir)), + "Offset of field: RTCRay::dir", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).align1) as usize - ptr as usize }, 28usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(align1)), + "Offset of field: RTCRay::align1", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tnear) as usize - ptr as usize }, 32usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(tnear)), + "Offset of field: RTCRay::tnear", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tfar) as usize - ptr as usize }, 36usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(tfar)), + "Offset of field: RTCRay::tfar", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).time) as usize - ptr as usize }, 40usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(time)), + "Offset of field: RTCRay::time", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mask) as usize - ptr as usize }, 44usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(mask)), + "Offset of field: RTCRay::mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).Ng) as usize - ptr as usize }, 48usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(Ng)), + "Offset of field: RTCRay::Ng", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).align2) as usize - ptr as usize }, 60usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(align2)), + "Offset of field: RTCRay::align2", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, 64usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(u)), + "Offset of field: RTCRay::u", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).v) as usize - ptr as usize }, 68usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(v)), + "Offset of field: RTCRay::v", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).geomID) as usize - ptr as usize }, 72usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(geomID)), + "Offset of field: RTCRay::geomID", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).primID) as usize - ptr as usize }, 76usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(primID)), + "Offset of field: RTCRay::primID", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).instID) as usize - ptr as usize }, 80usize, - concat!("Offset of field: ", stringify!(RTCRay), "::", stringify!(instID)), + "Offset of field: RTCRay::instID", ); } diff --git a/bindgen-tests/tests/expectations/tests/issue-1350-attribute-overloadable.rs b/bindgen-tests/tests/expectations/tests/issue-1350-attribute-overloadable.rs index 908ccfbc2e..c033570793 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1350-attribute-overloadable.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1350-attribute-overloadable.rs @@ -1,9 +1,9 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z11my_functioni"] pub fn my_function(a: ::std::os::raw::c_int); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z11my_functionPKc"] pub fn my_function1(a: *const ::std::os::raw::c_char); } diff --git a/bindgen-tests/tests/expectations/tests/issue-1375-prefixed-functions.rs b/bindgen-tests/tests/expectations/tests/issue-1375-prefixed-functions.rs index 2e9a594a31..f5e231ea96 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1375-prefixed-functions.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1375-prefixed-functions.rs @@ -1,13 +1,13 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}my_custom_prefix_var_const_name"] pub static var_const_name: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}my_custom_prefix_var_mut_name"] pub static mut var_mut_name: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}my_custom_prefix_function_name"] pub fn function_name(x: ::std::os::raw::c_int); } diff --git a/bindgen-tests/tests/expectations/tests/issue-1382-rust-primitive-types.rs b/bindgen-tests/tests/expectations/tests/issue-1382-rust-primitive-types.rs index 8dbed446af..277978d93c 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1382-rust-primitive-types.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1382-rust-primitive-types.rs @@ -25,88 +25,22 @@ pub struct Foo { pub f32_: ::std::os::raw::c_int, pub f64_: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 56usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i8_) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(i8_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u8_) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(u8_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i16_) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(i16_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u16_) as usize - ptr as usize }, - 12usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(u16_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i32_) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(i32_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u32_) as usize - ptr as usize }, - 20usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(u32_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i64_) as usize - ptr as usize }, - 24usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(i64_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u64_) as usize - ptr as usize }, - 28usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(u64_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i128_) as usize - ptr as usize }, - 32usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(i128_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u128_) as usize - ptr as usize }, - 36usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(u128_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).isize_) as usize - ptr as usize }, - 40usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(isize_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).usize_) as usize - ptr as usize }, - 44usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(usize_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f32_) as usize - ptr as usize }, - 48usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(f32_)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f64_) as usize - ptr as usize }, - 52usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(f64_)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 56usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo::i8_"][::std::mem::offset_of!(Foo, i8_) - 0usize]; + ["Offset of field: Foo::u8_"][::std::mem::offset_of!(Foo, u8_) - 4usize]; + ["Offset of field: Foo::i16_"][::std::mem::offset_of!(Foo, i16_) - 8usize]; + ["Offset of field: Foo::u16_"][::std::mem::offset_of!(Foo, u16_) - 12usize]; + ["Offset of field: Foo::i32_"][::std::mem::offset_of!(Foo, i32_) - 16usize]; + ["Offset of field: Foo::u32_"][::std::mem::offset_of!(Foo, u32_) - 20usize]; + ["Offset of field: Foo::i64_"][::std::mem::offset_of!(Foo, i64_) - 24usize]; + ["Offset of field: Foo::u64_"][::std::mem::offset_of!(Foo, u64_) - 28usize]; + ["Offset of field: Foo::i128_"][::std::mem::offset_of!(Foo, i128_) - 32usize]; + ["Offset of field: Foo::u128_"][::std::mem::offset_of!(Foo, u128_) - 36usize]; + ["Offset of field: Foo::isize_"][::std::mem::offset_of!(Foo, isize_) - 40usize]; + ["Offset of field: Foo::usize_"][::std::mem::offset_of!(Foo, usize_) - 44usize]; + ["Offset of field: Foo::f32_"][::std::mem::offset_of!(Foo, f32_) - 48usize]; + ["Offset of field: Foo::f64_"][::std::mem::offset_of!(Foo, f64_) - 52usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-1435.rs b/bindgen-tests/tests/expectations/tests/issue-1435.rs index 3040c1451e..b50e1f88c0 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1435.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1435.rs @@ -6,12 +6,12 @@ pub mod root { pub mod ns { #[allow(unused_imports)] use self::super::super::root; - pub const AB_A: root::ns::AB = 0; - pub const AB_B: root::ns::AB = 1; + pub const AB_A: AB = 0; + pub const AB_B: AB = 1; pub type AB = ::std::os::raw::c_int; } pub use self::super::root::ns::AB as AB; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZL2kA"] pub static kA: root::AB; } diff --git a/bindgen-tests/tests/expectations/tests/issue-1443.rs b/bindgen-tests/tests/expectations/tests/issue-1443.rs index 16ad2ca437..ee1ffca8e5 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1443.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1443.rs @@ -10,31 +10,13 @@ pub struct Bar { pub f: *const Foo, pub m: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(f)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(m)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 16usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::f"][::std::mem::offset_of!(Bar, f) - 0usize]; + ["Offset of field: Bar::m"][::std::mem::offset_of!(Bar, m) - 8usize]; +}; impl Default for Bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -50,31 +32,13 @@ pub struct Baz { pub f: *mut Foo, pub m: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_Baz() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Baz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Baz), "::", stringify!(f)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Baz), "::", stringify!(m)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Baz"][::std::mem::size_of::() - 16usize]; + ["Alignment of Baz"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Baz::f"][::std::mem::offset_of!(Baz, f) - 0usize]; + ["Offset of field: Baz::m"][::std::mem::offset_of!(Baz, m) - 8usize]; +}; impl Default for Baz { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -90,31 +54,13 @@ pub struct Tar { pub f: *const Foo, pub m: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_Tar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Tar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Tar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Tar), "::", stringify!(f)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Tar), "::", stringify!(m)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Tar"][::std::mem::size_of::() - 16usize]; + ["Alignment of Tar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Tar::f"][::std::mem::offset_of!(Tar, f) - 0usize]; + ["Offset of field: Tar::m"][::std::mem::offset_of!(Tar, m) - 8usize]; +}; impl Default for Tar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -130,31 +76,13 @@ pub struct Taz { pub f: *mut Foo, pub m: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_Taz() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Taz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Taz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).f) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Taz), "::", stringify!(f)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Taz), "::", stringify!(m)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Taz"][::std::mem::size_of::() - 16usize]; + ["Alignment of Taz"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Taz::f"][::std::mem::offset_of!(Taz, f) - 0usize]; + ["Offset of field: Taz::m"][::std::mem::offset_of!(Taz, m) - 8usize]; +}; impl Default for Taz { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/issue-1454.rs b/bindgen-tests/tests/expectations/tests/issue-1454.rs index 9a6052c9ea..325ccfd977 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1454.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1454.rs @@ -7,23 +7,11 @@ pub struct extern_type; pub struct local_type { pub inner: extern_type, } -#[test] -fn bindgen_test_layout_local_type() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(local_type)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(local_type)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).inner) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(local_type), "::", stringify!(inner)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of local_type"][::std::mem::size_of::() - 0usize]; + ["Alignment of local_type"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: local_type::inner", + ][::std::mem::offset_of!(local_type, inner) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-1498.rs b/bindgen-tests/tests/expectations/tests/issue-1498.rs index 342fcc0869..286d2eb6ee 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1498.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1498.rs @@ -24,41 +24,21 @@ pub union rte_memseg__bindgen_ty_1 { ///< Makes sure addr is always 64 bits pub addr_64: u64, } -#[test] -fn bindgen_test_layout_rte_memseg__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_memseg__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_memseg__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).addr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_memseg__bindgen_ty_1), - "::", - stringify!(addr), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).addr_64) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_memseg__bindgen_ty_1), - "::", - stringify!(addr_64), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_memseg__bindgen_ty_1", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of rte_memseg__bindgen_ty_1", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: rte_memseg__bindgen_ty_1::addr", + ][::std::mem::offset_of!(rte_memseg__bindgen_ty_1, addr) - 0usize]; + [ + "Offset of field: rte_memseg__bindgen_ty_1::addr_64", + ][::std::mem::offset_of!(rte_memseg__bindgen_ty_1, addr_64) - 0usize]; +}; impl Default for rte_memseg__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -68,56 +48,29 @@ impl Default for rte_memseg__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_rte_memseg() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 44usize, - concat!("Size of: ", stringify!(rte_memseg)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(rte_memseg)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).phys_addr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_memseg), "::", stringify!(phys_addr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).len) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(rte_memseg), "::", stringify!(len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hugepage_sz) as usize - ptr as usize }, - 24usize, - concat!( - "Offset of field: ", - stringify!(rte_memseg), - "::", - stringify!(hugepage_sz), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).socket_id) as usize - ptr as usize }, - 32usize, - concat!("Offset of field: ", stringify!(rte_memseg), "::", stringify!(socket_id)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nchannel) as usize - ptr as usize }, - 36usize, - concat!("Offset of field: ", stringify!(rte_memseg), "::", stringify!(nchannel)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nrank) as usize - ptr as usize }, - 40usize, - concat!("Offset of field: ", stringify!(rte_memseg), "::", stringify!(nrank)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_memseg"][::std::mem::size_of::() - 44usize]; + ["Alignment of rte_memseg"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: rte_memseg::phys_addr", + ][::std::mem::offset_of!(rte_memseg, phys_addr) - 0usize]; + [ + "Offset of field: rte_memseg::len", + ][::std::mem::offset_of!(rte_memseg, len) - 16usize]; + [ + "Offset of field: rte_memseg::hugepage_sz", + ][::std::mem::offset_of!(rte_memseg, hugepage_sz) - 24usize]; + [ + "Offset of field: rte_memseg::socket_id", + ][::std::mem::offset_of!(rte_memseg, socket_id) - 32usize]; + [ + "Offset of field: rte_memseg::nchannel", + ][::std::mem::offset_of!(rte_memseg, nchannel) - 36usize]; + [ + "Offset of field: rte_memseg::nrank", + ][::std::mem::offset_of!(rte_memseg, nrank) - 40usize]; +}; impl Default for rte_memseg { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/issue-1514.rs b/bindgen-tests/tests/expectations/tests/issue-1514.rs index a52272ef93..aef63037ae 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1514.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1514.rs @@ -7,8 +7,8 @@ pub struct Thing { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Thing_Inner { - pub ptr: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub ptr: *mut T, } impl Default for Thing_Inner { fn default() -> Self { @@ -22,8 +22,8 @@ impl Default for Thing_Inner { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Thing_AnotherInner { - pub _base: Thing_Inner, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub _base: Thing_Inner, } impl Default for Thing_AnotherInner { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/issue-1947.rs b/bindgen-tests/tests/expectations/tests/issue-1947.rs index be623357d0..cceb42d8c5 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1947.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1947.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } pub type U8 = ::std::os::raw::c_uchar; pub type U16 = ::std::os::raw::c_ushort; @@ -96,36 +158,14 @@ pub struct V56AMDY { pub _bitfield_2: __BindgenBitfieldUnit<[u8; 3usize]>, pub _rB_: U8, } -#[test] -fn bindgen_test_layout_V56AMDY() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(V56AMDY)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(V56AMDY)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).MADK) as usize - ptr as usize }, - 2usize, - concat!("Offset of field: ", stringify!(V56AMDY), "::", stringify!(MADK)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).MABR) as usize - ptr as usize }, - 3usize, - concat!("Offset of field: ", stringify!(V56AMDY), "::", stringify!(MABR)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr)._rB_) as usize - ptr as usize }, - 7usize, - concat!("Offset of field: ", stringify!(V56AMDY), "::", stringify!(_rB_)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of V56AMDY"][::std::mem::size_of::() - 8usize]; + ["Alignment of V56AMDY"][::std::mem::align_of::() - 2usize]; + ["Offset of field: V56AMDY::MADK"][::std::mem::offset_of!(V56AMDY, MADK) - 2usize]; + ["Offset of field: V56AMDY::MABR"][::std::mem::offset_of!(V56AMDY, MABR) - 3usize]; + ["Offset of field: V56AMDY::_rB_"][::std::mem::offset_of!(V56AMDY, _rB_) - 7usize]; +}; impl V56AMDY { #[inline] pub fn MADZ(&self) -> U16 { @@ -139,6 +179,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MADZ_raw(this: *const Self) -> U16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 10u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_MADZ_raw(this: *mut Self, val: U16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 10u8, + val as u64, + ) + } + } + #[inline] pub fn MAI0(&self) -> U16 { unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 2u8) as u16) } } @@ -150,6 +215,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MAI0_raw(this: *const Self) -> U16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 10usize, 2u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_MAI0_raw(this: *mut Self, val: U16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 2u8, + val as u64, + ) + } + } + #[inline] pub fn MAI1(&self) -> U16 { unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 2u8) as u16) } } @@ -161,6 +251,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MAI1_raw(this: *const Self) -> U16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 12usize, 2u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_MAI1_raw(this: *mut Self, val: U16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 2u8, + val as u64, + ) + } + } + #[inline] pub fn MAI2(&self) -> U16 { unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 2u8) as u16) } } @@ -172,6 +287,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MAI2_raw(this: *const Self) -> U16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 14usize, 2u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_MAI2_raw(this: *mut Self, val: U16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 2u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( MADZ: U16, MAI0: U16, @@ -229,6 +369,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MATH_raw(this: *const Self) -> U16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 0usize, 10u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_MATH_raw(this: *mut Self, val: U16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 0usize, + 10u8, + val as u64, + ) + } + } + #[inline] pub fn MATE(&self) -> U16 { unsafe { ::std::mem::transmute(self._bitfield_2.get(10usize, 4u8) as u16) } } @@ -240,6 +405,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MATE_raw(this: *const Self) -> U16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 10usize, 4u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_MATE_raw(this: *mut Self, val: U16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 10usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn MATW(&self) -> U16 { unsafe { ::std::mem::transmute(self._bitfield_2.get(14usize, 2u8) as u16) } } @@ -251,6 +441,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MATW_raw(this: *const Self) -> U16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 14usize, 2u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_MATW_raw(this: *mut Self, val: U16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 14usize, + 2u8, + val as u64, + ) + } + } + #[inline] pub fn MASW(&self) -> U8 { unsafe { ::std::mem::transmute(self._bitfield_2.get(16usize, 4u8) as u8) } } @@ -262,6 +477,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MASW_raw(this: *const Self) -> U8 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 16usize, 4u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_MASW_raw(this: *mut Self, val: U8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 16usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn MABW(&self) -> U8 { unsafe { ::std::mem::transmute(self._bitfield_2.get(20usize, 3u8) as u8) } } @@ -273,6 +513,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MABW_raw(this: *const Self) -> U8 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 20usize, 3u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_MABW_raw(this: *mut Self, val: U8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 20usize, + 3u8, + val as u64, + ) + } + } + #[inline] pub fn MAXN(&self) -> U8 { unsafe { ::std::mem::transmute(self._bitfield_2.get(23usize, 1u8) as u8) } } @@ -284,6 +549,31 @@ impl V56AMDY { } } #[inline] + pub unsafe fn MAXN_raw(this: *const Self) -> U8 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 23usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_MAXN_raw(this: *mut Self, val: U8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 23usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_2( MATH: U16, MATE: U16, diff --git a/bindgen-tests/tests/expectations/tests/issue-1977-larger-arrays.rs b/bindgen-tests/tests/expectations/tests/issue-1977-larger-arrays.rs index f60e10cdff..df7a2192ed 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1977-larger-arrays.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1977-larger-arrays.rs @@ -4,22 +4,12 @@ pub struct S { pub large_array: [::std::os::raw::c_char; 33usize], } -#[test] -fn bindgen_test_layout_S() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 33usize, concat!("Size of: ", stringify!(S))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(S)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).large_array) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(S), "::", stringify!(large_array)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of S"][::std::mem::size_of::() - 33usize]; + ["Alignment of S"][::std::mem::align_of::() - 1usize]; + ["Offset of field: S::large_array"][::std::mem::offset_of!(S, large_array) - 0usize]; +}; impl Default for S { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -32,8 +22,8 @@ impl Default for S { #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct ST { - pub large_array: [T; 33usize], pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub large_array: [T; 33usize], } impl Default for ST { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/issue-1995.rs b/bindgen-tests/tests/expectations/tests/issue-1995.rs index c0964371e9..0e36bdd9c9 100644 --- a/bindgen-tests/tests/expectations/tests/issue-1995.rs +++ b/bindgen-tests/tests/expectations/tests/issue-1995.rs @@ -11,23 +11,9 @@ pub const FOO: ::std::os::raw::c_int = 1; pub struct Bar { pub baz: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Bar::baz"][::std::mem::offset_of!(Bar, baz) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-2019.rs b/bindgen-tests/tests/expectations/tests/issue-2019.rs index 6dbbc3b0c8..4c91cf9972 100644 --- a/bindgen-tests/tests/expectations/tests/issue-2019.rs +++ b/bindgen-tests/tests/expectations/tests/issue-2019.rs @@ -4,23 +4,13 @@ pub struct A { pub a: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(a)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 4usize]; + ["Alignment of A"][::std::mem::align_of::() - 4usize]; + ["Offset of field: A::a"][::std::mem::offset_of!(A, a) - 0usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN1A4makeEv"] pub fn make() -> A; } @@ -35,23 +25,13 @@ impl A { pub struct B { pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_B() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(B)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(B), "::", stringify!(b)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of B"][::std::mem::size_of::() - 4usize]; + ["Alignment of B"][::std::mem::align_of::() - 4usize]; + ["Offset of field: B::b"][::std::mem::offset_of!(B, b) - 0usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN1B4makeEv"] pub fn make1() -> B; } diff --git a/bindgen-tests/tests/expectations/tests/issue-2556.rs b/bindgen-tests/tests/expectations/tests/issue-2556.rs index 54b0b5ec54..92fe5026b8 100644 --- a/bindgen-tests/tests/expectations/tests/issue-2556.rs +++ b/bindgen-tests/tests/expectations/tests/issue-2556.rs @@ -9,35 +9,21 @@ pub mod root { pub width: ::std::os::raw::c_int, pub height: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_nsSize() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsSize)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(nsSize)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).width) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsSize), "::", stringify!(width)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).height) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(nsSize), "::", stringify!(height)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of nsSize"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsSize"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: nsSize::width", + ][::std::mem::offset_of!(nsSize, width) - 0usize]; + [ + "Offset of field: nsSize::height", + ][::std::mem::offset_of!(nsSize, height) - 4usize]; + }; pub mod foo { #[allow(unused_imports)] use self::super::super::root; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN3fooL22kFallbackIntrinsicSizeE"] pub static kFallbackIntrinsicSize: root::nsSize; } diff --git a/bindgen-tests/tests/expectations/tests/issue-2695.rs b/bindgen-tests/tests/expectations/tests/issue-2695.rs index ed559fb606..20a016dbab 100644 --- a/bindgen-tests/tests/expectations/tests/issue-2695.rs +++ b/bindgen-tests/tests/expectations/tests/issue-2695.rs @@ -8,38 +8,12 @@ pub struct Test { pub c: ::std::os::raw::c_char, pub __bindgen_padding_0: u8, } -#[test] -fn bindgen_test_layout_Test() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(Test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(Test)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 9usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 10usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(c)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 12usize]; + ["Alignment of Test"][::std::mem::align_of::() - 2usize]; + ["Offset of field: Test::x"][::std::mem::offset_of!(Test, x) - 0usize]; + ["Offset of field: Test::a"][::std::mem::offset_of!(Test, a) - 8usize]; + ["Offset of field: Test::b"][::std::mem::offset_of!(Test, b) - 9usize]; + ["Offset of field: Test::c"][::std::mem::offset_of!(Test, c) - 10usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-2966.rs b/bindgen-tests/tests/expectations/tests/issue-2966.rs new file mode 100644 index 0000000000..bfdcbd9e2f --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/issue-2966.rs @@ -0,0 +1,10 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(transparent)] +#[derive(Debug, Copy, Clone)] +pub struct pub_var1(pub *const ::std::os::raw::c_char); +#[repr(transparent)] +#[derive(Debug, Copy, Clone)] +pub struct pubcrate_var2(pub(crate) *const ::std::os::raw::c_char); +#[repr(transparent)] +#[derive(Debug, Copy, Clone)] +pub struct private_var3(*const ::std::os::raw::c_char); diff --git a/bindgen-tests/tests/expectations/tests/issue-3027.rs b/bindgen-tests/tests/expectations/tests/issue-3027.rs new file mode 100644 index 0000000000..757aa9d9df --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/issue-3027.rs @@ -0,0 +1,31 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub mod root { + /// If Bindgen could only determine the size and alignment of a + /// type, it is represented like this. + #[derive(PartialEq, Copy, Clone, Debug, Hash)] + #[repr(C)] + pub struct __BindgenOpaqueArray(pub [T; N]); + impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } + } + #[allow(unused_imports)] + use self::super::root; + pub mod regression { + #[allow(unused_imports)] + use self::super::super::root; + #[repr(C)] + #[derive(Debug, Default, Copy, Clone)] + pub struct C { + pub a: root::__BindgenOpaqueArray, + } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of C"][::std::mem::size_of::() - 3usize]; + ["Alignment of C"][::std::mem::align_of::() - 1usize]; + ["Offset of field: C::a"][::std::mem::offset_of!(C, a) - 0usize]; + }; + } +} diff --git a/bindgen-tests/tests/expectations/tests/issue-372.rs b/bindgen-tests/tests/expectations/tests/issue-372.rs index 3155676176..80b8cbe8b6 100644 --- a/bindgen-tests/tests/expectations/tests/issue-372.rs +++ b/bindgen-tests/tests/expectations/tests/issue-372.rs @@ -14,30 +14,22 @@ pub mod root { fn bindgen_test_layout_i() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(i)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(i)), - ); + assert_eq!(::std::mem::size_of::(), 24usize, "Size of i"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of i"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).j) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(i), "::", stringify!(j)), + "Offset of field: i::j", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).k) as usize - ptr as usize }, 8usize, - concat!("Offset of field: ", stringify!(i), "::", stringify!(k)), + "Offset of field: i::k", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).l) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(i), "::", stringify!(l)), + "Offset of field: i::l", ); } impl Default for i { @@ -58,20 +50,12 @@ pub mod root { fn bindgen_test_layout_d() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(d)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(d)), - ); + assert_eq!(::std::mem::size_of::(), 24usize, "Size of d"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of d"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).m) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(d), "::", stringify!(m)), + "Offset of field: d::m", ); } impl Default for d { @@ -107,20 +91,12 @@ pub mod root { fn bindgen_test_layout_F() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 264usize, - concat!("Size of: ", stringify!(F)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(F)), - ); + assert_eq!(::std::mem::size_of::(), 264usize, "Size of F"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of F"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).w) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(F), "::", stringify!(w)), + "Offset of field: F::w", ); } impl Default for F { diff --git a/bindgen-tests/tests/expectations/tests/issue-410.rs b/bindgen-tests/tests/expectations/tests/issue-410.rs index d04cafe8df..cda9b6e338 100644 --- a/bindgen-tests/tests/expectations/tests/issue-410.rs +++ b/bindgen-tests/tests/expectations/tests/issue-410.rs @@ -11,20 +11,12 @@ pub mod root { pub struct Value { pub _address: u8, } - #[test] - fn bindgen_test_layout_Value() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Value)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Value)), - ); - } - extern "C" { + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Value"][::std::mem::size_of::() - 1usize]; + ["Alignment of Value"][::std::mem::align_of::() - 1usize]; + }; + unsafe extern "C" { #[link_name = "\u{1}_ZN2JS5Value1aE10JSWhyMagic"] pub fn Value_a(this: *mut root::JS::Value, arg1: root::JSWhyMagic); } diff --git a/bindgen-tests/tests/expectations/tests/issue-447.rs b/bindgen-tests/tests/expectations/tests/issue-447.rs index 1f1e376b5c..8867a359a2 100644 --- a/bindgen-tests/tests/expectations/tests/issue-447.rs +++ b/bindgen-tests/tests/expectations/tests/issue-447.rs @@ -14,19 +14,15 @@ pub mod root { pub struct GuardObjectNotifier { pub _address: u8, } - #[test] - fn bindgen_test_layout_GuardObjectNotifier() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(GuardObjectNotifier)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(GuardObjectNotifier)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of GuardObjectNotifier", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of GuardObjectNotifier", + ][::std::mem::align_of::() - 1usize]; + }; } } #[repr(C)] @@ -34,20 +30,16 @@ pub mod root { pub struct JSAutoCompartment { pub _address: u8, } - #[test] - fn bindgen_test_layout_JSAutoCompartment() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(JSAutoCompartment)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(JSAutoCompartment)), - ); - } - extern "C" { + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of JSAutoCompartment", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of JSAutoCompartment", + ][::std::mem::align_of::() - 1usize]; + }; + unsafe extern "C" { #[link_name = "\u{1}_ZN17JSAutoCompartmentC1EN7mozilla6detail19GuardObjectNotifierE"] pub fn JSAutoCompartment_JSAutoCompartment( this: *mut root::JSAutoCompartment, diff --git a/bindgen-tests/tests/expectations/tests/issue-493_1_0.rs b/bindgen-tests/tests/expectations/tests/issue-493_1_0.rs deleted file mode 100644 index ff0c93428b..0000000000 --- a/bindgen-tests/tests/expectations/tests/issue-493_1_0.rs +++ /dev/null @@ -1,136 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct basic_string { - pub _address: u8, -} -pub type basic_string_size_type = ::std::os::raw::c_ulonglong; -pub type basic_string_value_type = ::std::os::raw::c_char; -pub type basic_string_pointer = *mut basic_string_value_type; -#[repr(C)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub struct basic_string___long { - pub __cap_: basic_string_size_type, - pub __size_: basic_string_size_type, - pub __data_: basic_string_pointer, -} -impl Default for basic_string___long { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -pub const basic_string___min_cap: basic_string__bindgen_ty_1 = basic_string__bindgen_ty_1::__min_cap; -#[repr(i32)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum basic_string__bindgen_ty_1 { - __min_cap = 0, -} -#[repr(C)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub struct basic_string___short { - pub __bindgen_anon_1: basic_string___short__bindgen_ty_1, - pub __data_: *mut basic_string_value_type, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct basic_string___short__bindgen_ty_1 { - pub __size_: __BindgenUnionField<::std::os::raw::c_uchar>, - pub __lx: __BindgenUnionField, - pub bindgen_union_field: u8, -} -impl Default for basic_string___short { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct basic_string___ulx { - pub __lx: __BindgenUnionField, - pub __lxx: __BindgenUnionField, - pub bindgen_union_field: [u8; 0usize], -} -pub const basic_string___n_words: basic_string__bindgen_ty_2 = basic_string__bindgen_ty_2::__n_words; -#[repr(i32)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum basic_string__bindgen_ty_2 { - __n_words = 0, -} -#[repr(C)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub struct basic_string___raw { - pub __words: *mut basic_string_size_type, -} -impl Default for basic_string___raw { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct basic_string___rep { - pub __bindgen_anon_1: basic_string___rep__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct basic_string___rep__bindgen_ty_1 { - pub __l: __BindgenUnionField, - pub __s: __BindgenUnionField, - pub __r: __BindgenUnionField, - pub bindgen_union_field: [u8; 0usize], -} diff --git a/bindgen-tests/tests/expectations/tests/issue-511.rs b/bindgen-tests/tests/expectations/tests/issue-511.rs index e2bb991946..9d26b334c3 100644 --- a/bindgen-tests/tests/expectations/tests/issue-511.rs +++ b/bindgen-tests/tests/expectations/tests/issue-511.rs @@ -1,13 +1,13 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub static mut a: *mut ::std::os::raw::c_char; } -extern "C" { +unsafe extern "C" { pub static mut b: *const ::std::os::raw::c_char; } -extern "C" { +unsafe extern "C" { pub static c: *mut ::std::os::raw::c_char; } -extern "C" { +unsafe extern "C" { pub static d: *const ::std::os::raw::c_char; } diff --git a/bindgen-tests/tests/expectations/tests/issue-537-repr-packed-n.rs b/bindgen-tests/tests/expectations/tests/issue-537-repr-packed-n.rs index 387082d0c8..0142673f3e 100644 --- a/bindgen-tests/tests/expectations/tests/issue-537-repr-packed-n.rs +++ b/bindgen-tests/tests/expectations/tests/issue-537-repr-packed-n.rs @@ -11,23 +11,19 @@ pub struct AlignedToOne { fn bindgen_test_layout_AlignedToOne() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(AlignedToOne)), - ); + assert_eq!(::std::mem::size_of::(), 4usize, "Size of AlignedToOne"); assert_eq!( ::std::mem::align_of::(), 1usize, - concat!("Alignment of ", stringify!(AlignedToOne)), + "Alignment of AlignedToOne", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(AlignedToOne), "::", stringify!(i)), + "Offset of field: AlignedToOne::i", ); } -/// This should be be packed because Rust 1.33 has `#[repr(packed(N))]`. +/// This should be packed because Rust 1.33 has `#[repr(packed(N))]`. #[repr(C, packed(2))] #[derive(Debug, Default, Copy, Clone)] pub struct AlignedToTwo { @@ -37,20 +33,16 @@ pub struct AlignedToTwo { fn bindgen_test_layout_AlignedToTwo() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(AlignedToTwo)), - ); + assert_eq!(::std::mem::size_of::(), 4usize, "Size of AlignedToTwo"); assert_eq!( ::std::mem::align_of::(), 2usize, - concat!("Alignment of ", stringify!(AlignedToTwo)), + "Alignment of AlignedToTwo", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(AlignedToTwo), "::", stringify!(i)), + "Offset of field: AlignedToTwo::i", ); } /** This should not be opaque because although `libclang` doesn't give us the @@ -66,28 +58,24 @@ pub struct PackedToOne { fn bindgen_test_layout_PackedToOne() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(PackedToOne)), - ); + assert_eq!(::std::mem::size_of::(), 8usize, "Size of PackedToOne"); assert_eq!( ::std::mem::align_of::(), 1usize, - concat!("Alignment of ", stringify!(PackedToOne)), + "Alignment of PackedToOne", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(PackedToOne), "::", stringify!(x)), + "Offset of field: PackedToOne::x", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(PackedToOne), "::", stringify!(y)), + "Offset of field: PackedToOne::y", ); } -/// This should be be packed because Rust 1.33 has `#[repr(packed(N))]`. +/// This should be packed because Rust 1.33 has `#[repr(packed(N))]`. #[repr(C, packed(2))] #[derive(Debug, Default, Copy, Clone)] pub struct PackedToTwo { @@ -98,24 +86,20 @@ pub struct PackedToTwo { fn bindgen_test_layout_PackedToTwo() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(PackedToTwo)), - ); + assert_eq!(::std::mem::size_of::(), 8usize, "Size of PackedToTwo"); assert_eq!( ::std::mem::align_of::(), 2usize, - concat!("Alignment of ", stringify!(PackedToTwo)), + "Alignment of PackedToTwo", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(PackedToTwo), "::", stringify!(x)), + "Offset of field: PackedToTwo::x", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(PackedToTwo), "::", stringify!(y)), + "Offset of field: PackedToTwo::y", ); } diff --git a/bindgen-tests/tests/expectations/tests/issue-537.rs b/bindgen-tests/tests/expectations/tests/issue-537.rs index c9ce3fb035..d630b9ea4c 100644 --- a/bindgen-tests/tests/expectations/tests/issue-537.rs +++ b/bindgen-tests/tests/expectations/tests/issue-537.rs @@ -6,26 +6,14 @@ pub struct AlignedToOne { pub i: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_AlignedToOne() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(AlignedToOne)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(AlignedToOne)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AlignedToOne), "::", stringify!(i)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AlignedToOne"][::std::mem::size_of::() - 4usize]; + ["Alignment of AlignedToOne"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: AlignedToOne::i", + ][::std::mem::offset_of!(AlignedToOne, i) - 0usize]; +}; /** This should be opaque because although we can see the attributes, Rust before 1.33 doesn't have `#[repr(packed(N))]`.*/ #[repr(C, packed(2))] @@ -33,26 +21,14 @@ fn bindgen_test_layout_AlignedToOne() { pub struct AlignedToTwo { pub i: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_AlignedToTwo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(AlignedToTwo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(AlignedToTwo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AlignedToTwo), "::", stringify!(i)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AlignedToTwo"][::std::mem::size_of::() - 4usize]; + ["Alignment of AlignedToTwo"][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: AlignedToTwo::i", + ][::std::mem::offset_of!(AlignedToTwo, i) - 0usize]; +}; /** This should not be opaque because although `libclang` doesn't give us the `#pragma pack(1)`, we can detect that alignment is 1 and add `#[repr(packed)]` to the struct ourselves.*/ @@ -62,31 +38,13 @@ pub struct PackedToOne { pub x: ::std::os::raw::c_int, pub y: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_PackedToOne() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(PackedToOne)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(PackedToOne)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(PackedToOne), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(PackedToOne), "::", stringify!(y)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of PackedToOne"][::std::mem::size_of::() - 8usize]; + ["Alignment of PackedToOne"][::std::mem::align_of::() - 1usize]; + ["Offset of field: PackedToOne::x"][::std::mem::offset_of!(PackedToOne, x) - 0usize]; + ["Offset of field: PackedToOne::y"][::std::mem::offset_of!(PackedToOne, y) - 4usize]; +}; /** In this case, even if we can detect the weird alignment triggered by `#pragma pack(2)`, we can't do anything about it because Rust before 1.33 doesn't have `#[repr(packed(N))]`. Therefore, we must make it opaque.*/ @@ -96,28 +54,10 @@ pub struct PackedToTwo { pub x: ::std::os::raw::c_int, pub y: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_PackedToTwo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(PackedToTwo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(PackedToTwo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(PackedToTwo), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(PackedToTwo), "::", stringify!(y)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of PackedToTwo"][::std::mem::size_of::() - 8usize]; + ["Alignment of PackedToTwo"][::std::mem::align_of::() - 2usize]; + ["Offset of field: PackedToTwo::x"][::std::mem::offset_of!(PackedToTwo, x) - 0usize]; + ["Offset of field: PackedToTwo::y"][::std::mem::offset_of!(PackedToTwo, y) - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-544-stylo-creduce-2.rs b/bindgen-tests/tests/expectations/tests/issue-544-stylo-creduce-2.rs index c81b672956..8a752f6999 100644 --- a/bindgen-tests/tests/expectations/tests/issue-544-stylo-creduce-2.rs +++ b/bindgen-tests/tests/expectations/tests/issue-544-stylo-creduce-2.rs @@ -1,10 +1,20 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +/// If Bindgen could only determine the size and alignment of a +/// type, it is represented like this. +#[derive(PartialEq, Copy, Clone, Debug, Hash)] +#[repr(C)] +pub struct __BindgenOpaqueArray(pub [T; N]); +impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } +} #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Foo { pub member: *mut Foo_SecondAlias, } -pub type Foo_FirstAlias = [u8; 0usize]; +pub type Foo_FirstAlias = __BindgenOpaqueArray; pub type Foo_SecondAlias = Foo; impl Default for Foo { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/issue-569-non-type-template-params-causing-layout-test-failures.rs b/bindgen-tests/tests/expectations/tests/issue-569-non-type-template-params-causing-layout-test-failures.rs index 59590ec8fe..567325b82d 100644 --- a/bindgen-tests/tests/expectations/tests/issue-569-non-type-template-params-causing-layout-test-failures.rs +++ b/bindgen-tests/tests/expectations/tests/issue-569-non-type-template-params-causing-layout-test-failures.rs @@ -27,19 +27,11 @@ impl Default for JS_Base { pub struct JS_AutoIdVector { pub _base: JS_Base, } -#[test] -fn bindgen_test_layout_JS_AutoIdVector() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(JS_AutoIdVector)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(JS_AutoIdVector)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of JS_AutoIdVector"][::std::mem::size_of::() - 1usize]; + ["Alignment of JS_AutoIdVector"][::std::mem::align_of::() - 1usize]; +}; impl Default for JS_AutoIdVector { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -49,16 +41,12 @@ impl Default for JS_AutoIdVector { } } } -#[test] -fn __bindgen_test_layout_JS_Base_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(JS_Base)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(JS_Base)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: JS_Base_open0_int_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: JS_Base_open0_int_close0", + ][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-573-layout-test-failures.rs b/bindgen-tests/tests/expectations/tests/issue-573-layout-test-failures.rs index ab51dc8943..aa5f457792 100644 --- a/bindgen-tests/tests/expectations/tests/issue-573-layout-test-failures.rs +++ b/bindgen-tests/tests/expectations/tests/issue-573-layout-test-failures.rs @@ -9,36 +9,20 @@ pub struct Outer { pub struct AutoIdVector { pub ar: Outer, } -#[test] -fn bindgen_test_layout_AutoIdVector() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(AutoIdVector)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(AutoIdVector)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(AutoIdVector), "::", stringify!(ar)), - ); -} -#[test] -fn __bindgen_test_layout_Outer_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(Outer)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(Outer)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AutoIdVector"][::std::mem::size_of::() - 1usize]; + ["Alignment of AutoIdVector"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: AutoIdVector::ar", + ][::std::mem::offset_of!(AutoIdVector, ar) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Outer_open0_int_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: Outer_open0_int_close0", + ][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-574-assertion-failure-in-codegen.rs b/bindgen-tests/tests/expectations/tests/issue-574-assertion-failure-in-codegen.rs index d3c0cee41c..9968501397 100644 --- a/bindgen-tests/tests/expectations/tests/issue-574-assertion-failure-in-codegen.rs +++ b/bindgen-tests/tests/expectations/tests/issue-574-assertion-failure-in-codegen.rs @@ -9,39 +9,23 @@ pub struct a { pub struct _bindgen_ty_1 { pub ar: a, } -#[test] -fn bindgen_test_layout__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit<_bindgen_ty_1> = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::<_bindgen_ty_1>(), - 1usize, - concat!("Size of: ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::<_bindgen_ty_1>(), - 1usize, - concat!("Alignment of ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(_bindgen_ty_1), "::", stringify!(ar)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of _bindgen_ty_1"][::std::mem::size_of::<_bindgen_ty_1>() - 1usize]; + ["Alignment of _bindgen_ty_1"][::std::mem::align_of::<_bindgen_ty_1>() - 1usize]; + [ + "Offset of field: _bindgen_ty_1::ar", + ][::std::mem::offset_of!(_bindgen_ty_1, ar) - 0usize]; +}; +unsafe extern "C" { pub static mut AutoIdVector: _bindgen_ty_1; } -#[test] -fn __bindgen_test_layout_a_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(a)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: a_open0_int_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: a_open0_int_close0", + ][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-584-stylo-template-analysis-panic.rs b/bindgen-tests/tests/expectations/tests/issue-584-stylo-template-analysis-panic.rs index 060db1636d..2a85837e3d 100644 --- a/bindgen-tests/tests/expectations/tests/issue-584-stylo-template-analysis-panic.rs +++ b/bindgen-tests/tests/expectations/tests/issue-584-stylo-template-analysis-panic.rs @@ -6,19 +6,15 @@ pub struct A { pub _address: u8, } pub type A_a = b; -#[test] -fn bindgen_test_layout_A() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(A)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 1usize]; + ["Alignment of A"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] pub struct e { - pub d: RefPtr, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub d: RefPtr, } impl Default for e { fn default() -> Self { @@ -38,22 +34,12 @@ pub struct f { pub struct g { pub h: f, } -#[test] -fn bindgen_test_layout_g() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(g))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(g)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).h) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(g), "::", stringify!(h)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of g"][::std::mem::size_of::() - 1usize]; + ["Alignment of g"][::std::mem::align_of::() - 1usize]; + ["Offset of field: g::h"][::std::mem::offset_of!(g, h) - 0usize]; +}; impl Default for g { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -67,15 +53,11 @@ impl Default for g { pub struct b { pub _base: g, } -#[test] -fn bindgen_test_layout_b() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(b))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of b"][::std::mem::size_of::() - 1usize]; + ["Alignment of b"][::std::mem::align_of::() - 1usize]; +}; impl Default for b { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -85,20 +67,16 @@ impl Default for b { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z25Servo_Element_GetSnapshotv"] pub fn Servo_Element_GetSnapshot() -> A; } -#[test] -fn __bindgen_test_layout_f_open0_e_open1_int_close1_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(f)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(f)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: f_open0_e_open1_int_close1_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: f_open0_e_open1_int_close1_close0", + ][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-638-stylo-cannot-find-T-in-this-scope.rs b/bindgen-tests/tests/expectations/tests/issue-638-stylo-cannot-find-T-in-this-scope.rs index 292fa2734f..db94687737 100644 --- a/bindgen-tests/tests/expectations/tests/issue-638-stylo-cannot-find-T-in-this-scope.rs +++ b/bindgen-tests/tests/expectations/tests/issue-638-stylo-cannot-find-T-in-this-scope.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RefPtr { - pub use_of_t: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub use_of_t: T, } impl Default for RefPtr { fn default() -> Self { @@ -17,8 +17,8 @@ impl Default for RefPtr { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct UsesRefPtrWithAliasedTypeParam { - pub member: RefPtr>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member: RefPtr>, } pub type UsesRefPtrWithAliasedTypeParam_V = U; impl Default for UsesRefPtrWithAliasedTypeParam { diff --git a/bindgen-tests/tests/expectations/tests/issue-639-typedef-anon-field.rs b/bindgen-tests/tests/expectations/tests/issue-639-typedef-anon-field.rs index 2495b458e4..e940db1103 100644 --- a/bindgen-tests/tests/expectations/tests/issue-639-typedef-anon-field.rs +++ b/bindgen-tests/tests/expectations/tests/issue-639-typedef-anon-field.rs @@ -9,46 +9,18 @@ pub struct Foo { pub struct Foo_Bar { pub abc: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Foo_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Foo_Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo_Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).abc) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo_Bar), "::", stringify!(abc)), - ); -} -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo_Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Foo_Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo_Bar::abc"][::std::mem::offset_of!(Foo_Bar, abc) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo::bar"][::std::mem::offset_of!(Foo, bar) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Baz { @@ -59,36 +31,14 @@ pub struct Baz { pub struct Baz_Bar { pub abc: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Baz_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Baz_Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Baz_Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).abc) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Baz_Bar), "::", stringify!(abc)), - ); -} -#[test] -fn bindgen_test_layout_Baz() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Baz_Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Baz_Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Baz_Bar::abc"][::std::mem::offset_of!(Baz_Bar, abc) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Baz"][::std::mem::size_of::() - 1usize]; + ["Alignment of Baz"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-643-inner-struct.rs b/bindgen-tests/tests/expectations/tests/issue-643-inner-struct.rs index 520b3b0ecd..0012c8f6aa 100644 --- a/bindgen-tests/tests/expectations/tests/issue-643-inner-struct.rs +++ b/bindgen-tests/tests/expectations/tests/issue-643-inner-struct.rs @@ -42,96 +42,42 @@ pub struct rte_ring { pub struct rte_ring_prod { pub watermark: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_rte_ring_prod() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ring_prod)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ring_prod)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).watermark) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ring_prod), - "::", - stringify!(watermark), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_ring_prod"][::std::mem::size_of::() - 4usize]; + ["Alignment of rte_ring_prod"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_ring_prod::watermark", + ][::std::mem::offset_of!(rte_ring_prod, watermark) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct rte_ring_cons { pub sc_dequeue: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_rte_ring_cons() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_ring_cons)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_ring_cons)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sc_dequeue) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ring_cons), - "::", - stringify!(sc_dequeue), - ), - ); -} -#[test] -fn bindgen_test_layout_rte_ring() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(rte_ring)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_ring)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).memzone) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_ring), "::", stringify!(memzone)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).prod) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(rte_ring), "::", stringify!(prod)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cons) as usize - ptr as usize }, - 12usize, - concat!("Offset of field: ", stringify!(rte_ring), "::", stringify!(cons)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ring) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(rte_ring), "::", stringify!(ring)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_ring_cons"][::std::mem::size_of::() - 4usize]; + ["Alignment of rte_ring_cons"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_ring_cons::sc_dequeue", + ][::std::mem::offset_of!(rte_ring_cons, sc_dequeue) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_ring"][::std::mem::size_of::() - 16usize]; + ["Alignment of rte_ring"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: rte_ring::memzone", + ][::std::mem::offset_of!(rte_ring, memzone) - 0usize]; + ["Offset of field: rte_ring::prod"][::std::mem::offset_of!(rte_ring, prod) - 8usize]; + [ + "Offset of field: rte_ring::cons", + ][::std::mem::offset_of!(rte_ring, cons) - 12usize]; + [ + "Offset of field: rte_ring::ring", + ][::std::mem::offset_of!(rte_ring, ring) - 16usize]; +}; impl Default for rte_ring { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/issue-645-cannot-find-type-T-in-this-scope.rs b/bindgen-tests/tests/expectations/tests/issue-645-cannot-find-type-T-in-this-scope.rs index 3e3e398006..82e2ab4c42 100644 --- a/bindgen-tests/tests/expectations/tests/issue-645-cannot-find-type-T-in-this-scope.rs +++ b/bindgen-tests/tests/expectations/tests/issue-645-cannot-find-type-T-in-this-scope.rs @@ -3,8 +3,8 @@ pub struct RefPtr(T); #[repr(C)] pub struct HasRefPtr { - pub refptr_member: RefPtr>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub refptr_member: RefPtr>, } pub type HasRefPtr_TypedefOfT = T; impl Default for HasRefPtr { diff --git a/bindgen-tests/tests/expectations/tests/issue-648-derive-debug-with-padding.rs b/bindgen-tests/tests/expectations/tests/issue-648-derive-debug-with-padding.rs index 6015618d48..08e47bc2c6 100644 --- a/bindgen-tests/tests/expectations/tests/issue-648-derive-debug-with-padding.rs +++ b/bindgen-tests/tests/expectations/tests/issue-648-derive-debug-with-padding.rs @@ -11,20 +11,12 @@ pub struct NoDebug { fn bindgen_test_layout_NoDebug() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 64usize, - concat!("Size of: ", stringify!(NoDebug)), - ); - assert_eq!( - ::std::mem::align_of::(), - 64usize, - concat!("Alignment of ", stringify!(NoDebug)), - ); + assert_eq!(::std::mem::size_of::(), 64usize, "Size of NoDebug"); + assert_eq!(::std::mem::align_of::(), 64usize, "Alignment of NoDebug"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(NoDebug), "::", stringify!(c)), + "Offset of field: NoDebug::c", ); } impl Default for NoDebug { @@ -59,32 +51,22 @@ fn bindgen_test_layout_ShouldDeriveDebugButDoesNot() { assert_eq!( ::std::mem::size_of::(), 64usize, - concat!("Size of: ", stringify!(ShouldDeriveDebugButDoesNot)), + "Size of ShouldDeriveDebugButDoesNot", ); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(ShouldDeriveDebugButDoesNot)), + "Alignment of ShouldDeriveDebugButDoesNot", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(ShouldDeriveDebugButDoesNot), - "::", - stringify!(c), - ), + "Offset of field: ShouldDeriveDebugButDoesNot::c", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, 32usize, - concat!( - "Offset of field: ", - stringify!(ShouldDeriveDebugButDoesNot), - "::", - stringify!(d), - ), + "Offset of field: ShouldDeriveDebugButDoesNot::d", ); } impl Default for ShouldDeriveDebugButDoesNot { diff --git a/bindgen-tests/tests/expectations/tests/issue-654-struct-fn-collision.rs b/bindgen-tests/tests/expectations/tests/issue-654-struct-fn-collision.rs index 289dac9a1c..6bf02be74e 100644 --- a/bindgen-tests/tests/expectations/tests/issue-654-struct-fn-collision.rs +++ b/bindgen-tests/tests/expectations/tests/issue-654-struct-fn-collision.rs @@ -4,6 +4,6 @@ pub struct foo { _unused: [u8; 0], } -extern "C" { +unsafe extern "C" { pub fn foo() -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/issue-662-cannot-find-T-in-this-scope.rs b/bindgen-tests/tests/expectations/tests/issue-662-cannot-find-T-in-this-scope.rs index 5e6dd01298..2e68628323 100644 --- a/bindgen-tests/tests/expectations/tests/issue-662-cannot-find-T-in-this-scope.rs +++ b/bindgen-tests/tests/expectations/tests/issue-662-cannot-find-T-in-this-scope.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RefPtr { - pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub a: T, } impl Default for RefPtr { fn default() -> Self { @@ -17,8 +17,8 @@ impl Default for RefPtr { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHolder { - pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub a: T, } impl Default for nsMainThreadPtrHolder { fn default() -> Self { @@ -32,8 +32,8 @@ impl Default for nsMainThreadPtrHolder { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHandle { - pub mPtr: RefPtr>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub mPtr: RefPtr>, } impl Default for nsMainThreadPtrHandle { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/issue-662-part-2.rs b/bindgen-tests/tests/expectations/tests/issue-662-part-2.rs index 75993a052d..9ddcdc5e8d 100644 --- a/bindgen-tests/tests/expectations/tests/issue-662-part-2.rs +++ b/bindgen-tests/tests/expectations/tests/issue-662-part-2.rs @@ -4,8 +4,8 @@ pub struct RefPtr(T); #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHolder { - pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub a: T, } impl Default for nsMainThreadPtrHolder { fn default() -> Self { @@ -18,8 +18,8 @@ impl Default for nsMainThreadPtrHolder { } #[repr(C)] pub struct nsMainThreadPtrHandle { - pub mPtr: RefPtr>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub mPtr: RefPtr>, } impl Default for nsMainThreadPtrHandle { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/issue-674-1.rs b/bindgen-tests/tests/expectations/tests/issue-674-1.rs index 2173924c3c..1a3dce44d0 100644 --- a/bindgen-tests/tests/expectations/tests/issue-674-1.rs +++ b/bindgen-tests/tests/expectations/tests/issue-674-1.rs @@ -18,29 +18,16 @@ pub mod root { pub struct CapturingContentInfo { pub a: u8, } - #[test] - fn bindgen_test_layout_CapturingContentInfo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(CapturingContentInfo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(CapturingContentInfo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(CapturingContentInfo), - "::", - stringify!(a), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of CapturingContentInfo", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of CapturingContentInfo", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: CapturingContentInfo::a", + ][::std::mem::offset_of!(CapturingContentInfo, a) - 0usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/issue-674-2.rs b/bindgen-tests/tests/expectations/tests/issue-674-2.rs index 01f54798d7..980928fe97 100644 --- a/bindgen-tests/tests/expectations/tests/issue-674-2.rs +++ b/bindgen-tests/tests/expectations/tests/issue-674-2.rs @@ -18,70 +18,35 @@ pub mod root { pub struct c { pub b: u8, } - #[test] - fn bindgen_test_layout_c() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(c)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(c)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(c), "::", stringify!(b)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of c"][::std::mem::size_of::() - 1usize]; + ["Alignment of c"][::std::mem::align_of::() - 1usize]; + ["Offset of field: c::b"][::std::mem::offset_of!(c, b) - 0usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct B { pub a: root::c, } - #[test] - fn bindgen_test_layout_B() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(B)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(B)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(B), "::", stringify!(a)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of B"][::std::mem::size_of::() - 1usize]; + ["Alignment of B"][::std::mem::align_of::() - 1usize]; + ["Offset of field: B::a"][::std::mem::offset_of!(B, a) - 0usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct StaticRefPtr { pub _address: u8, } - #[test] - fn __bindgen_test_layout_StaticRefPtr_open0_B_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(root::StaticRefPtr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!( - "Alignment of template specialization: ", - stringify!(root::StaticRefPtr), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of template specialization: StaticRefPtr_open0_B_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: StaticRefPtr_open0_B_close0", + ][::std::mem::align_of::() - 1usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/issue-674-3.rs b/bindgen-tests/tests/expectations/tests/issue-674-3.rs index bba2f38b43..4e2f26a46f 100644 --- a/bindgen-tests/tests/expectations/tests/issue-674-3.rs +++ b/bindgen-tests/tests/expectations/tests/issue-674-3.rs @@ -14,49 +14,23 @@ pub mod root { pub struct a { pub b: u8, } - #[test] - fn bindgen_test_layout_a() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(a)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(a), "::", stringify!(b)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of a"][::std::mem::size_of::() - 1usize]; + ["Alignment of a"][::std::mem::align_of::() - 1usize]; + ["Offset of field: a::b"][::std::mem::offset_of!(a, b) - 0usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct nsCSSValue { pub c: root::a, } - #[test] - fn bindgen_test_layout_nsCSSValue() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(nsCSSValue)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(nsCSSValue)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsCSSValue), "::", stringify!(c)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of nsCSSValue"][::std::mem::size_of::() - 1usize]; + ["Alignment of nsCSSValue"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: nsCSSValue::c", + ][::std::mem::offset_of!(nsCSSValue, c) - 0usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/issue-691-template-parameter-virtual.rs b/bindgen-tests/tests/expectations/tests/issue-691-template-parameter-virtual.rs index 7080f2048b..1313d61168 100644 --- a/bindgen-tests/tests/expectations/tests/issue-691-template-parameter-virtual.rs +++ b/bindgen-tests/tests/expectations/tests/issue-691-template-parameter-virtual.rs @@ -6,19 +6,11 @@ pub struct VirtualMethods__bindgen_vtable {} pub struct VirtualMethods { pub vtable_: *const VirtualMethods__bindgen_vtable, } -#[test] -fn bindgen_test_layout_VirtualMethods() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(VirtualMethods)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(VirtualMethods)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of VirtualMethods"][::std::mem::size_of::() - 8usize]; + ["Alignment of VirtualMethods"][::std::mem::align_of::() - 8usize]; +}; impl Default for VirtualMethods { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -38,19 +30,15 @@ pub struct Set { pub struct ServoElementSnapshotTable { pub _base: Set, } -#[test] -fn bindgen_test_layout_ServoElementSnapshotTable() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(ServoElementSnapshotTable)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ServoElementSnapshotTable)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ServoElementSnapshotTable", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of ServoElementSnapshotTable", + ][::std::mem::align_of::() - 4usize]; +}; impl Default for ServoElementSnapshotTable { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -60,16 +48,12 @@ impl Default for ServoElementSnapshotTable { } } } -#[test] -fn __bindgen_test_layout_Set_open0_VirtualMethods_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of template specialization: ", stringify!(Set)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of template specialization: ", stringify!(Set)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Set_open0_VirtualMethods_close0", + ][::std::mem::size_of::() - 4usize]; + [ + "Align of template specialization: Set_open0_VirtualMethods_close0", + ][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-739-pointer-wide-bitfield.rs b/bindgen-tests/tests/expectations/tests/issue-739-pointer-wide-bitfield.rs index 7bc9933697..4e79cfdf71 100644 --- a/bindgen-tests/tests/expectations/tests/issue-739-pointer-wide-bitfield.rs +++ b/bindgen-tests/tests/expectations/tests/issue-739-pointer-wide-bitfield.rs @@ -16,10 +16,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -29,21 +26,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -66,6 +90,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -83,6 +127,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -90,19 +152,11 @@ pub struct Foo { pub _bitfield_align_1: [u64; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 32usize]>, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 32usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 32usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 8usize]; +}; impl Foo { #[inline] pub fn m_bitfield(&self) -> ::std::os::raw::c_ulong { @@ -116,6 +170,31 @@ impl Foo { } } #[inline] + pub unsafe fn m_bitfield_raw(this: *const Self) -> ::std::os::raw::c_ulong { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 32usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 64u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_m_bitfield_raw(this: *mut Self, val: ::std::os::raw::c_ulong) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 32usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 64u8, + val as u64, + ) + } + } + #[inline] pub fn m_bar(&self) -> ::std::os::raw::c_ulong { unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 64u8) as u64) } } @@ -127,6 +206,31 @@ impl Foo { } } #[inline] + pub unsafe fn m_bar_raw(this: *const Self) -> ::std::os::raw::c_ulong { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 32usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 64usize, 64u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_m_bar_raw(this: *mut Self, val: ::std::os::raw::c_ulong) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 32usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 64u8, + val as u64, + ) + } + } + #[inline] pub fn foo(&self) -> ::std::os::raw::c_ulong { unsafe { ::std::mem::transmute(self._bitfield_1.get(128usize, 1u8) as u64) } } @@ -138,6 +242,31 @@ impl Foo { } } #[inline] + pub unsafe fn foo_raw(this: *const Self) -> ::std::os::raw::c_ulong { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 32usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 128usize, 1u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_foo_raw(this: *mut Self, val: ::std::os::raw::c_ulong) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 32usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 128usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bar(&self) -> ::std::os::raw::c_ulong { unsafe { ::std::mem::transmute(self._bitfield_1.get(192usize, 64u8) as u64) } } @@ -149,6 +278,31 @@ impl Foo { } } #[inline] + pub unsafe fn bar_raw(this: *const Self) -> ::std::os::raw::c_ulong { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 32usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 192usize, 64u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_bar_raw(this: *mut Self, val: ::std::os::raw::c_ulong) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 32usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 192usize, + 64u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( m_bitfield: ::std::os::raw::c_ulong, m_bar: ::std::os::raw::c_ulong, diff --git a/bindgen-tests/tests/expectations/tests/issue-753.rs b/bindgen-tests/tests/expectations/tests/issue-753.rs new file mode 100644 index 0000000000..3119ec569e --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/issue-753.rs @@ -0,0 +1,4 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub const CONST: u32 = 5; +pub const OTHER_CONST: u32 = 6; +pub const LARGE_CONST: u32 = 1536; diff --git a/bindgen-tests/tests/expectations/tests/issue-769-bad-instantiation-test.rs b/bindgen-tests/tests/expectations/tests/issue-769-bad-instantiation-test.rs index ef830ca69e..59a1d9afa3 100644 --- a/bindgen-tests/tests/expectations/tests/issue-769-bad-instantiation-test.rs +++ b/bindgen-tests/tests/expectations/tests/issue-769-bad-instantiation-test.rs @@ -6,8 +6,8 @@ pub mod root { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Rooted { - pub member: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member: T, } impl Default for Rooted { fn default() -> Self { @@ -19,42 +19,22 @@ pub mod root { } } pub type AutoValueVector_Alias = ::std::os::raw::c_int; - #[test] - fn __bindgen_test_layout_Rooted_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(root::Rooted < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(root::Rooted < ::std::os::raw::c_int >), - ), - ); - } - #[test] - fn __bindgen_test_layout_Rooted_open0_AutoValueVector_Alias_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(root::Rooted < root::AutoValueVector_Alias >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(root::Rooted < root::AutoValueVector_Alias >), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of template specialization: Rooted_open0_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: Rooted_open0_int_close0", + ][::std::mem::align_of::>() - 4usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of template specialization: Rooted_open0_AutoValueVector_Alias_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: Rooted_open0_AutoValueVector_Alias_close0", + ][::std::mem::align_of::>() - 4usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/issue-801-opaque-sloppiness.rs b/bindgen-tests/tests/expectations/tests/issue-801-opaque-sloppiness.rs index cf68821f18..90eb048640 100644 --- a/bindgen-tests/tests/expectations/tests/issue-801-opaque-sloppiness.rs +++ b/bindgen-tests/tests/expectations/tests/issue-801-opaque-sloppiness.rs @@ -10,16 +10,12 @@ pub struct A { pub struct B { pub _bindgen_opaque_blob: u8, } -#[test] -fn bindgen_test_layout_B() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(B)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of B"][::std::mem::size_of::() - 1usize]; + ["Alignment of B"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN1B1aE"] pub static mut B_a: A; } @@ -28,19 +24,9 @@ extern "C" { pub struct C { pub b: B, } -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 1usize]; + ["Alignment of C"][::std::mem::align_of::() - 1usize]; + ["Offset of field: C::b"][::std::mem::offset_of!(C, b) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-807-opaque-types-methods-being-generated.rs b/bindgen-tests/tests/expectations/tests/issue-807-opaque-types-methods-being-generated.rs index ab807045be..3d3ee5e590 100644 --- a/bindgen-tests/tests/expectations/tests/issue-807-opaque-types-methods-being-generated.rs +++ b/bindgen-tests/tests/expectations/tests/issue-807-opaque-types-methods-being-generated.rs @@ -4,79 +4,47 @@ pub struct Pupper { pub _address: u8, } -#[test] -fn bindgen_test_layout_Pupper() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Pupper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Pupper)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Pupper"][::std::mem::size_of::() - 1usize]; + ["Alignment of Pupper"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct Doggo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Doggo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Doggo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Doggo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Doggo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Doggo"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct SuchWow { pub _address: u8, } -#[test] -fn bindgen_test_layout_SuchWow() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(SuchWow)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(SuchWow)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of SuchWow"][::std::mem::size_of::() - 1usize]; + ["Alignment of SuchWow"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[repr(align(1))] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct Opaque { pub _bindgen_opaque_blob: u8, } -#[test] -fn bindgen_test_layout_Opaque() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Opaque)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Opaque)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Opaque"][::std::mem::size_of::() - 1usize]; + ["Alignment of Opaque"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN6Opaque17eleven_out_of_tenEv"] pub fn Opaque_eleven_out_of_ten(this: *mut Opaque) -> SuchWow; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN6OpaqueC1E6Pupper"] pub fn Opaque_Opaque(this: *mut Opaque, pup: Pupper); } @@ -92,7 +60,7 @@ impl Opaque { __bindgen_tmp.assume_init() } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN6Opaque11MAJESTIC_AFE"] pub static mut Opaque_MAJESTIC_AF: Doggo; } @@ -101,28 +69,11 @@ extern "C" { pub struct Allowlisted { pub some_member: Opaque, } -#[test] -fn bindgen_test_layout_Allowlisted() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Allowlisted)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Allowlisted)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).some_member) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(Allowlisted), - "::", - stringify!(some_member), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Allowlisted"][::std::mem::size_of::() - 1usize]; + ["Alignment of Allowlisted"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: Allowlisted::some_member", + ][::std::mem::offset_of!(Allowlisted, some_member) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-816.rs b/bindgen-tests/tests/expectations/tests/issue-816.rs index 206e6ffd17..56e719238b 100644 --- a/bindgen-tests/tests/expectations/tests/issue-816.rs +++ b/bindgen-tests/tests/expectations/tests/issue-816.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[repr(align(4))] @@ -90,19 +152,11 @@ pub struct capabilities { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, } -#[test] -fn bindgen_test_layout_capabilities() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(capabilities)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(capabilities)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of capabilities"][::std::mem::size_of::() - 16usize]; + ["Alignment of capabilities"][::std::mem::align_of::() - 4usize]; +}; impl capabilities { #[inline] pub fn bit_1(&self) -> ::std::os::raw::c_uint { @@ -116,6 +170,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_1_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_1_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_2(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } } @@ -127,6 +206,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_2_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_2_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_3(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } } @@ -138,6 +242,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_3_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_3_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_4(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } } @@ -149,6 +278,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_4_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 3usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_4_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_5(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } } @@ -160,6 +314,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_5_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 4usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_5_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_6(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } } @@ -171,6 +350,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_6_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 5usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_6_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_7(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } } @@ -182,6 +386,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_7_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 6usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_7_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_8(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } } @@ -193,6 +422,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_8_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 7usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_8_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_9(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } } @@ -204,6 +458,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_9_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 8usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_9_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_10(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } } @@ -215,6 +494,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_10_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 9usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_10_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_11(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } } @@ -226,6 +530,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_11_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 10usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_11_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_12(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u32) } } @@ -237,6 +566,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_12_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 11usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_12_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_13(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } } @@ -248,6 +602,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_13_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 12usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_13_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_14(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } } @@ -259,6 +638,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_14_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 13usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_14_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_15(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 1u8) as u32) } } @@ -270,6 +674,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_15_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 14usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_15_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_16(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 1u8) as u32) } } @@ -281,6 +710,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_16_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 15usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_16_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_17(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 1u8) as u32) } } @@ -292,6 +746,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_17_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_17_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_18(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(17usize, 1u8) as u32) } } @@ -303,6 +782,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_18_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 17usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_18_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 17usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_19(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 1u8) as u32) } } @@ -314,6 +818,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_19_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 18usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_19_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_20(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(19usize, 1u8) as u32) } } @@ -325,6 +854,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_20_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 19usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_20_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 19usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_21(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 1u8) as u32) } } @@ -336,6 +890,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_21_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 20usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_21_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_22(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(21usize, 1u8) as u32) } } @@ -347,6 +926,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_22_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 21usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_22_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 21usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_23(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(22usize, 1u8) as u32) } } @@ -358,6 +962,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_23_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 22usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_23_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 22usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_24(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(23usize, 1u8) as u32) } } @@ -369,6 +998,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_24_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 23usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_24_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 23usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_25(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 1u8) as u32) } } @@ -380,6 +1034,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_25_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 24usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_25_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_26(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(25usize, 1u8) as u32) } } @@ -391,6 +1070,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_26_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 25usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_26_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 25usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_27(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(26usize, 1u8) as u32) } } @@ -402,6 +1106,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_27_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 26usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_27_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 26usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_28(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(27usize, 1u8) as u32) } } @@ -413,6 +1142,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_28_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 27usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_28_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 27usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_29(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(28usize, 1u8) as u32) } } @@ -424,6 +1178,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_29_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 28usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_29_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 28usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_30(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(29usize, 1u8) as u32) } } @@ -435,6 +1214,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_30_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 29usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_30_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 29usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_31(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(30usize, 1u8) as u32) } } @@ -446,6 +1250,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_31_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 30usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_31_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 30usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_32(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(31usize, 1u8) as u32) } } @@ -457,6 +1286,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_32_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 31usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_32_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 31usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_33(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 1u8) as u32) } } @@ -468,6 +1322,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_33_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 32usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_33_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_34(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(33usize, 1u8) as u32) } } @@ -479,6 +1358,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_34_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 33usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_34_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 33usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_35(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(34usize, 1u8) as u32) } } @@ -490,6 +1394,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_35_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 34usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_35_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 34usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_36(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(35usize, 1u8) as u32) } } @@ -501,6 +1430,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_36_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 35usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_36_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 35usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_37(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(36usize, 1u8) as u32) } } @@ -512,6 +1466,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_37_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 36usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_37_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 36usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_38(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(37usize, 1u8) as u32) } } @@ -523,6 +1502,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_38_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 37usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_38_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 37usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_39(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(38usize, 1u8) as u32) } } @@ -534,6 +1538,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_39_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 38usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_39_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 38usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_40(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(39usize, 1u8) as u32) } } @@ -545,6 +1574,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_40_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 39usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_40_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 39usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn bit_41(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(40usize, 1u8) as u32) } } @@ -556,6 +1610,31 @@ impl capabilities { } } #[inline] + pub unsafe fn bit_41_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 40usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bit_41_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 16usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 40usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( bit_1: ::std::os::raw::c_uint, bit_2: ::std::os::raw::c_uint, diff --git a/bindgen-tests/tests/expectations/tests/issue-826-generating-methods-when-asked-not-to.rs b/bindgen-tests/tests/expectations/tests/issue-826-generating-methods-when-asked-not-to.rs index d51ccfa80c..551dff82cf 100644 --- a/bindgen-tests/tests/expectations/tests/issue-826-generating-methods-when-asked-not-to.rs +++ b/bindgen-tests/tests/expectations/tests/issue-826-generating-methods-when-asked-not-to.rs @@ -4,16 +4,8 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-833-1.rs b/bindgen-tests/tests/expectations/tests/issue-833-1.rs index b86a4e0df3..5aa8c3078b 100644 --- a/bindgen-tests/tests/expectations/tests/issue-833-1.rs +++ b/bindgen-tests/tests/expectations/tests/issue-833-1.rs @@ -3,6 +3,6 @@ pub struct nsTArray { pub hdr: *const (), } -extern "C" { +unsafe extern "C" { pub fn func() -> *mut nsTArray; } diff --git a/bindgen-tests/tests/expectations/tests/issue-833.rs b/bindgen-tests/tests/expectations/tests/issue-833.rs index 2a2d375e89..9698fdb479 100644 --- a/bindgen-tests/tests/expectations/tests/issue-833.rs +++ b/bindgen-tests/tests/expectations/tests/issue-833.rs @@ -3,6 +3,6 @@ pub struct nsTArray { pub hdr: *const T, } -extern "C" { +unsafe extern "C" { pub fn func() -> *mut nsTArray<::std::os::raw::c_int>; } diff --git a/bindgen-tests/tests/expectations/tests/issue-834.rs b/bindgen-tests/tests/expectations/tests/issue-834.rs index 24c18c2be7..4119a450e0 100644 --- a/bindgen-tests/tests/expectations/tests/issue-834.rs +++ b/bindgen-tests/tests/expectations/tests/issue-834.rs @@ -4,12 +4,8 @@ pub struct U { pub _address: u8, } -#[test] -fn bindgen_test_layout_U() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(U))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(U)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of U"][::std::mem::size_of::() - 1usize]; + ["Alignment of U"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/issue-848-replacement-system-include.rs b/bindgen-tests/tests/expectations/tests/issue-848-replacement-system-include.rs index d9d4fd9abc..6beeae69d8 100644 --- a/bindgen-tests/tests/expectations/tests/issue-848-replacement-system-include.rs +++ b/bindgen-tests/tests/expectations/tests/issue-848-replacement-system-include.rs @@ -8,8 +8,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsTArray { - pub m: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub m: *mut T, } impl Default for nsTArray { fn default() -> Self { @@ -20,6 +20,6 @@ impl Default for nsTArray { } } } -extern "C" { +unsafe extern "C" { pub fn func() -> *mut nsTArray<::std::os::raw::c_int>; } diff --git a/bindgen-tests/tests/expectations/tests/issue-888-enum-var-decl-jump.rs b/bindgen-tests/tests/expectations/tests/issue-888-enum-var-decl-jump.rs index 974e191401..023c8695e3 100644 --- a/bindgen-tests/tests/expectations/tests/issue-888-enum-var-decl-jump.rs +++ b/bindgen-tests/tests/expectations/tests/issue-888-enum-var-decl-jump.rs @@ -11,23 +11,15 @@ pub mod root { pub struct Type { pub _address: u8, } - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN6Halide4Type1bE"] pub static mut Type_b: root::a; } - #[test] - fn bindgen_test_layout_Type() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Type)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Type)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Type"][::std::mem::size_of::() - 1usize]; + ["Alignment of Type"][::std::mem::align_of::() - 1usize]; + }; } #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] diff --git a/bindgen-tests/tests/expectations/tests/issue-944-derive-copy-and-blocklisting.rs b/bindgen-tests/tests/expectations/tests/issue-944-derive-copy-and-blocklisting.rs index a5cd116cfd..5e8dde04e3 100644 --- a/bindgen-tests/tests/expectations/tests/issue-944-derive-copy-and-blocklisting.rs +++ b/bindgen-tests/tests/expectations/tests/issue-944-derive-copy-and-blocklisting.rs @@ -5,26 +5,14 @@ pub struct BlocklistMe(u8); pub struct ShouldNotBeCopy { pub a: BlocklistMe, } -#[test] -fn bindgen_test_layout_ShouldNotBeCopy() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ShouldNotBeCopy)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ShouldNotBeCopy)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(ShouldNotBeCopy), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ShouldNotBeCopy"][::std::mem::size_of::() - 1usize]; + ["Alignment of ShouldNotBeCopy"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ShouldNotBeCopy::a", + ][::std::mem::offset_of!(ShouldNotBeCopy, a) - 0usize]; +}; impl Default for ShouldNotBeCopy { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/issue-946.rs b/bindgen-tests/tests/expectations/tests/issue-946.rs index a1bf320f1a..bdd56c0326 100644 --- a/bindgen-tests/tests/expectations/tests/issue-946.rs +++ b/bindgen-tests/tests/expectations/tests/issue-946.rs @@ -2,17 +2,9 @@ #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct foo {} -#[test] -fn bindgen_test_layout_foo() { - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 0usize]; + ["Alignment of foo"][::std::mem::align_of::() - 1usize]; +}; pub type bar = foo; diff --git a/bindgen-tests/tests/expectations/tests/issue_311.rs b/bindgen-tests/tests/expectations/tests/issue_311.rs index 8822aece04..2e0114e43e 100644 --- a/bindgen-tests/tests/expectations/tests/issue_311.rs +++ b/bindgen-tests/tests/expectations/tests/issue_311.rs @@ -13,30 +13,18 @@ pub mod root { pub struct jsval_layout__bindgen_ty_1 { pub _address: u8, } - #[test] - fn bindgen_test_layout_jsval_layout__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(jsval_layout__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(jsval_layout__bindgen_ty_1)), - ); - } - #[test] - fn bindgen_test_layout_jsval_layout() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(jsval_layout)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(jsval_layout)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of jsval_layout__bindgen_ty_1", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of jsval_layout__bindgen_ty_1", + ][::std::mem::align_of::() - 1usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of jsval_layout"][::std::mem::size_of::() - 1usize]; + ["Alignment of jsval_layout"][::std::mem::align_of::() - 1usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/jsval_layout_opaque.rs b/bindgen-tests/tests/expectations/tests/jsval_layout_opaque.rs index 576f57586a..7dd23241e9 100644 --- a/bindgen-tests/tests/expectations/tests/jsval_layout_opaque.rs +++ b/bindgen-tests/tests/expectations/tests/jsval_layout_opaque.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } pub const JSVAL_TAG_SHIFT: u32 = 47; pub const JSVAL_PAYLOAD_MASK: u64 = 140737488355327; @@ -186,19 +248,15 @@ pub struct jsval_layout__bindgen_ty_1 { pub _bitfield_align_1: [u64; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } -#[test] -fn bindgen_test_layout_jsval_layout__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(jsval_layout__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(jsval_layout__bindgen_ty_1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of jsval_layout__bindgen_ty_1", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of jsval_layout__bindgen_ty_1", + ][::std::mem::align_of::() - 8usize]; +}; impl Default for jsval_layout__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -221,6 +279,31 @@ impl jsval_layout__bindgen_ty_1 { } } #[inline] + pub unsafe fn payload47_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 47u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_payload47_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 47u8, + val as u64, + ) + } + } + #[inline] pub fn tag(&self) -> JSValueTag { unsafe { ::std::mem::transmute(self._bitfield_1.get(47usize, 17u8) as u32) } } @@ -232,6 +315,31 @@ impl jsval_layout__bindgen_ty_1 { } } #[inline] + pub unsafe fn tag_raw(this: *const Self) -> JSValueTag { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 47usize, 17u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_tag_raw(this: *mut Self, val: JSValueTag) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 47usize, + 17u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( payload47: u64, tag: JSValueTag, @@ -270,51 +378,24 @@ pub union jsval_layout__bindgen_ty_2__bindgen_ty_1 { pub u32_: u32, pub why: JSWhyMagic, } -#[test] -fn bindgen_test_layout_jsval_layout__bindgen_ty_2__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i32_) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(i32_), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u32_) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(u32_), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).why) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(why), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of jsval_layout__bindgen_ty_2__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of jsval_layout__bindgen_ty_2__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: jsval_layout__bindgen_ty_2__bindgen_ty_1::i32_", + ][::std::mem::offset_of!(jsval_layout__bindgen_ty_2__bindgen_ty_1, i32_) - 0usize]; + [ + "Offset of field: jsval_layout__bindgen_ty_2__bindgen_ty_1::u32_", + ][::std::mem::offset_of!(jsval_layout__bindgen_ty_2__bindgen_ty_1, u32_) - 0usize]; + [ + "Offset of field: jsval_layout__bindgen_ty_2__bindgen_ty_1::why", + ][::std::mem::offset_of!(jsval_layout__bindgen_ty_2__bindgen_ty_1, why) - 0usize]; +}; impl Default for jsval_layout__bindgen_ty_2__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -324,31 +405,18 @@ impl Default for jsval_layout__bindgen_ty_2__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_jsval_layout__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(jsval_layout__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(jsval_layout__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).payload) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout__bindgen_ty_2), - "::", - stringify!(payload), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of jsval_layout__bindgen_ty_2", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of jsval_layout__bindgen_ty_2", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: jsval_layout__bindgen_ty_2::payload", + ][::std::mem::offset_of!(jsval_layout__bindgen_ty_2, payload) - 0usize]; +}; impl Default for jsval_layout__bindgen_ty_2 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -358,71 +426,32 @@ impl Default for jsval_layout__bindgen_ty_2 { } } } -#[test] -fn bindgen_test_layout_jsval_layout() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(jsval_layout)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(jsval_layout)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asBits) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(jsval_layout), "::", stringify!(asBits)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).debugView) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout), - "::", - stringify!(debugView), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).s) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(jsval_layout), "::", stringify!(s)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asDouble) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout), - "::", - stringify!(asDouble), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asPtr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(jsval_layout), "::", stringify!(asPtr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asWord) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(jsval_layout), "::", stringify!(asWord)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asUIntPtr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout), - "::", - stringify!(asUIntPtr), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of jsval_layout"][::std::mem::size_of::() - 8usize]; + ["Alignment of jsval_layout"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: jsval_layout::asBits", + ][::std::mem::offset_of!(jsval_layout, asBits) - 0usize]; + [ + "Offset of field: jsval_layout::debugView", + ][::std::mem::offset_of!(jsval_layout, debugView) - 0usize]; + [ + "Offset of field: jsval_layout::s", + ][::std::mem::offset_of!(jsval_layout, s) - 0usize]; + [ + "Offset of field: jsval_layout::asDouble", + ][::std::mem::offset_of!(jsval_layout, asDouble) - 0usize]; + [ + "Offset of field: jsval_layout::asPtr", + ][::std::mem::offset_of!(jsval_layout, asPtr) - 0usize]; + [ + "Offset of field: jsval_layout::asWord", + ][::std::mem::offset_of!(jsval_layout, asWord) - 0usize]; + [ + "Offset of field: jsval_layout::asUIntPtr", + ][::std::mem::offset_of!(jsval_layout, asUIntPtr) - 0usize]; +}; impl Default for jsval_layout { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -437,26 +466,12 @@ impl Default for jsval_layout { pub struct Value { pub data: jsval_layout, } -#[test] -fn bindgen_test_layout_Value() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Value)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Value)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).data) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Value), "::", stringify!(data)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Value"][::std::mem::size_of::() - 8usize]; + ["Alignment of Value"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Value::data"][::std::mem::offset_of!(Value, data) - 0usize]; +}; impl Default for Value { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/jsval_layout_opaque_1_0.rs b/bindgen-tests/tests/expectations/tests/jsval_layout_opaque_1_0.rs deleted file mode 100644 index 0889b65232..0000000000 --- a/bindgen-tests/tests/expectations/tests/jsval_layout_opaque_1_0.rs +++ /dev/null @@ -1,502 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub struct __BindgenBitfieldUnit { - storage: Storage, -} -impl __BindgenBitfieldUnit { - #[inline] - pub fn new(storage: Storage) -> Self { - Self { storage } - } -} -impl __BindgenBitfieldUnit -where - Storage: AsRef<[u8]> + AsMut<[u8]>, -{ - #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - byte & mask == mask - } - #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } - } - #[inline] - pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - let mut val = 0; - for i in 0..(bit_width as usize) { - if self.get_bit(i + bit_offset) { - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - val |= 1 << index; - } - } - val - } - #[inline] - pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - for i in 0..(bit_width as usize) { - let mask = 1 << i; - let val_bit_is_set = val & mask == mask; - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - self.set_bit(index + bit_offset, val_bit_is_set); - } - } -} -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -pub const JSVAL_TAG_SHIFT: u32 = 47; -pub const JSVAL_PAYLOAD_MASK: u64 = 140737488355327; -pub const JSVAL_TAG_MASK: i64 = -140737488355328; -#[repr(u8)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum JSValueType { - JSVAL_TYPE_DOUBLE = 0, - JSVAL_TYPE_INT32 = 1, - JSVAL_TYPE_UNDEFINED = 2, - JSVAL_TYPE_BOOLEAN = 3, - JSVAL_TYPE_MAGIC = 4, - JSVAL_TYPE_STRING = 5, - JSVAL_TYPE_SYMBOL = 6, - JSVAL_TYPE_NULL = 7, - JSVAL_TYPE_OBJECT = 8, - JSVAL_TYPE_UNKNOWN = 32, - JSVAL_TYPE_MISSING = 33, -} -#[repr(u32)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum JSValueTag { - JSVAL_TAG_MAX_DOUBLE = 131056, - JSVAL_TAG_INT32 = 131057, - JSVAL_TAG_UNDEFINED = 131058, - JSVAL_TAG_STRING = 131061, - JSVAL_TAG_SYMBOL = 131062, - JSVAL_TAG_BOOLEAN = 131059, - JSVAL_TAG_MAGIC = 131060, - JSVAL_TAG_NULL = 131063, - JSVAL_TAG_OBJECT = 131064, -} -#[repr(u64)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum JSValueShiftedTag { - JSVAL_SHIFTED_TAG_MAX_DOUBLE = 18444492278190833663, - JSVAL_SHIFTED_TAG_INT32 = 18444633011384221696, - JSVAL_SHIFTED_TAG_UNDEFINED = 18444773748872577024, - JSVAL_SHIFTED_TAG_STRING = 18445195961337643008, - JSVAL_SHIFTED_TAG_SYMBOL = 18445336698825998336, - JSVAL_SHIFTED_TAG_BOOLEAN = 18444914486360932352, - JSVAL_SHIFTED_TAG_MAGIC = 18445055223849287680, - JSVAL_SHIFTED_TAG_NULL = 18445477436314353664, - JSVAL_SHIFTED_TAG_OBJECT = 18445618173802708992, -} -#[repr(u32)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum JSWhyMagic { - /// a hole in a native object's elements - JS_ELEMENTS_HOLE = 0, - /// there is not a pending iterator value - JS_NO_ITER_VALUE = 1, - /// exception value thrown when closing a generator - JS_GENERATOR_CLOSING = 2, - /// compiler sentinel value - JS_NO_CONSTANT = 3, - /// used in debug builds to catch tracing errors - JS_THIS_POISON = 4, - /// used in debug builds to catch tracing errors - JS_ARG_POISON = 5, - /// an empty subnode in the AST serializer - JS_SERIALIZE_NO_NODE = 6, - /// lazy arguments value on the stack - JS_LAZY_ARGUMENTS = 7, - /// optimized-away 'arguments' value - JS_OPTIMIZED_ARGUMENTS = 8, - /// magic value passed to natives to indicate construction - JS_IS_CONSTRUCTING = 9, - /// arguments.callee has been overwritten - JS_OVERWRITTEN_CALLEE = 10, - /// value of static block object slot - JS_BLOCK_NEEDS_CLONE = 11, - /// see class js::HashableValue - JS_HASH_KEY_EMPTY = 12, - /// error while running Ion code - JS_ION_ERROR = 13, - /// missing recover instruction result - JS_ION_BAILOUT = 14, - /// optimized out slot - JS_OPTIMIZED_OUT = 15, - /// uninitialized lexical bindings that produce ReferenceError on touch. - JS_UNINITIALIZED_LEXICAL = 16, - /// for local use - JS_GENERIC_MAGIC = 17, - /// for local use - JS_WHY_MAGIC_COUNT = 18, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq)] -pub struct jsval_layout { - pub asBits: __BindgenUnionField, - pub debugView: __BindgenUnionField, - pub s: __BindgenUnionField, - pub asDouble: __BindgenUnionField, - pub asPtr: __BindgenUnionField<*mut ::std::os::raw::c_void>, - pub asWord: __BindgenUnionField, - pub asUIntPtr: __BindgenUnionField, - pub bindgen_union_field: u64, -} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct jsval_layout__bindgen_ty_1 { - pub _bitfield_align_1: [u64; 0], - pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, -} -#[test] -fn bindgen_test_layout_jsval_layout__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(jsval_layout__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(jsval_layout__bindgen_ty_1)), - ); -} -impl Clone for jsval_layout__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -impl Default for jsval_layout__bindgen_ty_1 { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -impl jsval_layout__bindgen_ty_1 { - #[inline] - pub fn payload47(&self) -> u64 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 47u8) as u64) } - } - #[inline] - pub fn set_payload47(&mut self, val: u64) { - unsafe { - let val: u64 = ::std::mem::transmute(val); - self._bitfield_1.set(0usize, 47u8, val as u64) - } - } - #[inline] - pub fn tag(&self) -> JSValueTag { - unsafe { ::std::mem::transmute(self._bitfield_1.get(47usize, 17u8) as u32) } - } - #[inline] - pub fn set_tag(&mut self, val: JSValueTag) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(47usize, 17u8, val as u64) - } - } - #[inline] - pub fn new_bitfield_1( - payload47: u64, - tag: JSValueTag, - ) -> __BindgenBitfieldUnit<[u8; 8usize]> { - let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); - __bindgen_bitfield_unit - .set( - 0usize, - 47u8, - { - let payload47: u64 = unsafe { ::std::mem::transmute(payload47) }; - payload47 as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 47usize, - 17u8, - { - let tag: u32 = unsafe { ::std::mem::transmute(tag) }; - tag as u64 - }, - ); - __bindgen_bitfield_unit - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct jsval_layout__bindgen_ty_2 { - pub payload: jsval_layout__bindgen_ty_2__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct jsval_layout__bindgen_ty_2__bindgen_ty_1 { - pub i32_: __BindgenUnionField, - pub u32_: __BindgenUnionField, - pub why: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_jsval_layout__bindgen_ty_2__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i32_) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(i32_), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u32_) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(u32_), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).why) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(why), - ), - ); -} -impl Clone for jsval_layout__bindgen_ty_2__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_jsval_layout__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(jsval_layout__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(jsval_layout__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).payload) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout__bindgen_ty_2), - "::", - stringify!(payload), - ), - ); -} -impl Clone for jsval_layout__bindgen_ty_2 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_jsval_layout() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(jsval_layout)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(jsval_layout)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asBits) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(jsval_layout), "::", stringify!(asBits)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).debugView) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout), - "::", - stringify!(debugView), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).s) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(jsval_layout), "::", stringify!(s)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asDouble) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout), - "::", - stringify!(asDouble), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asPtr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(jsval_layout), "::", stringify!(asPtr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asWord) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(jsval_layout), "::", stringify!(asWord)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).asUIntPtr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(jsval_layout), - "::", - stringify!(asUIntPtr), - ), - ); -} -impl Clone for jsval_layout { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq)] -pub struct Value { - pub data: jsval_layout, -} -#[test] -fn bindgen_test_layout_Value() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Value)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Value)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).data) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Value), "::", stringify!(data)), - ); -} -impl Clone for Value { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/keywords.rs b/bindgen-tests/tests/expectations/tests/keywords.rs index d07f241376..0a55ee0463 100644 --- a/bindgen-tests/tests/expectations/tests/keywords.rs +++ b/bindgen-tests/tests/expectations/tests/keywords.rs @@ -1,221 +1,225 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}u8"] pub static mut u8_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}u16"] pub static mut u16_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}u32"] pub static mut u32_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}u64"] pub static mut u64_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}i8"] pub static mut i8_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}i16"] pub static mut i16_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}i32"] pub static mut i32_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}i64"] pub static mut i64_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}f32"] pub static mut f32_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}f64"] pub static mut f64_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}usize"] pub static mut usize_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}isize"] pub static mut isize_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}bool"] pub static mut bool_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}str"] pub static mut str_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}dyn"] pub static mut dyn_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}as"] pub static mut as_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}async"] pub static mut async_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}await"] pub static mut await_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}box"] pub static mut box_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}crate"] pub static mut crate_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}false"] pub static mut false_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}fn"] pub static mut fn_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { + #[link_name = "\u{1}gen"] + pub static mut gen_: ::std::os::raw::c_int; +} +unsafe extern "C" { #[link_name = "\u{1}impl"] pub static mut impl_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}in"] pub static mut in_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}let"] pub static mut let_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}loop"] pub static mut loop_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}match"] pub static mut match_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}mod"] pub static mut mod_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}move"] pub static mut move_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}mut"] pub static mut mut_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}pub"] pub static mut pub_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}ref"] pub static mut ref_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}self"] pub static mut self_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}Self"] pub static mut Self_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}super"] pub static mut super_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}trait"] pub static mut trait_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}true"] pub static mut true_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}try"] pub static mut try_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}type"] pub static mut type_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}unsafe"] pub static mut unsafe_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}use"] pub static mut use_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}where"] pub static mut where_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}abstract"] pub static mut abstract_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}alignof"] pub static mut alignof_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}become"] pub static mut become_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}final"] pub static mut final_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}macro"] pub static mut macro_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}offsetof"] pub static mut offsetof_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}override"] pub static mut override_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}priv"] pub static mut priv_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}proc"] pub static mut proc_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}pure"] pub static mut pure_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}unsized"] pub static mut unsized_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}virtual"] pub static mut virtual_: ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}yield"] pub static mut yield_: ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/layout.rs b/bindgen-tests/tests/expectations/tests/layout.rs index 2c7dc047ba..fe64295a68 100644 --- a/bindgen-tests/tests/expectations/tests/layout.rs +++ b/bindgen-tests/tests/expectations/tests/layout.rs @@ -1,22 +1 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct header { - pub _bindgen_opaque_blob: [u8; 16usize], -} -#[test] -fn bindgen_test_layout_header() { - assert_eq!( - ::std::mem::size_of::
(), - 16usize, - concat!("Size of: ", stringify!(header)), - ); -} -impl Default for header { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] \ No newline at end of file diff --git a/bindgen-tests/tests/expectations/tests/layout_align.rs b/bindgen-tests/tests/expectations/tests/layout_align.rs index be77dc75d4..18662d4c83 100644 --- a/bindgen-tests/tests/expectations/tests/layout_align.rs +++ b/bindgen-tests/tests/expectations/tests/layout_align.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Default)] @@ -127,51 +189,26 @@ pub struct rte_kni_fifo { ///< The buffer contains mbuf pointers pub buffer: __IncompleteArrayField<*mut ::std::os::raw::c_void>, } -#[test] -fn bindgen_test_layout_rte_kni_fifo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(rte_kni_fifo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_kni_fifo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).write) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_kni_fifo), "::", stringify!(write)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).read) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(rte_kni_fifo), "::", stringify!(read)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).len) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(rte_kni_fifo), "::", stringify!(len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).elem_size) as usize - ptr as usize }, - 12usize, - concat!( - "Offset of field: ", - stringify!(rte_kni_fifo), - "::", - stringify!(elem_size), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).buffer) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(rte_kni_fifo), "::", stringify!(buffer)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_kni_fifo"][::std::mem::size_of::() - 16usize]; + ["Alignment of rte_kni_fifo"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: rte_kni_fifo::write", + ][::std::mem::offset_of!(rte_kni_fifo, write) - 0usize]; + [ + "Offset of field: rte_kni_fifo::read", + ][::std::mem::offset_of!(rte_kni_fifo, read) - 4usize]; + [ + "Offset of field: rte_kni_fifo::len", + ][::std::mem::offset_of!(rte_kni_fifo, len) - 8usize]; + [ + "Offset of field: rte_kni_fifo::elem_size", + ][::std::mem::offset_of!(rte_kni_fifo, elem_size) - 12usize]; + [ + "Offset of field: rte_kni_fifo::buffer", + ][::std::mem::offset_of!(rte_kni_fifo, buffer) - 16usize]; +}; impl Default for rte_kni_fifo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -191,31 +228,14 @@ pub struct rte_eth_link { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub __bindgen_padding_0: [u8; 3usize], } -#[test] -fn bindgen_test_layout_rte_eth_link() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_eth_link)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_eth_link)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).link_speed) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_link), - "::", - stringify!(link_speed), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_eth_link"][::std::mem::size_of::() - 8usize]; + ["Alignment of rte_eth_link"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: rte_eth_link::link_speed", + ][::std::mem::offset_of!(rte_eth_link, link_speed) - 0usize]; +}; impl rte_eth_link { #[inline] pub fn link_duplex(&self) -> u16 { @@ -229,6 +249,31 @@ impl rte_eth_link { } } #[inline] + pub unsafe fn link_duplex_raw(this: *const Self) -> u16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_link_duplex_raw(this: *mut Self, val: u16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn link_autoneg(&self) -> u16 { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u16) } } @@ -240,6 +285,31 @@ impl rte_eth_link { } } #[inline] + pub unsafe fn link_autoneg_raw(this: *const Self) -> u16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_link_autoneg_raw(this: *mut Self, val: u16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn link_status(&self) -> u16 { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u16) } } @@ -251,6 +321,31 @@ impl rte_eth_link { } } #[inline] + pub unsafe fn link_status_raw(this: *const Self) -> u16 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 1u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_link_status_raw(this: *mut Self, val: u16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( link_duplex: u16, link_autoneg: u16, diff --git a/bindgen-tests/tests/expectations/tests/layout_arp.rs b/bindgen-tests/tests/expectations/tests/layout_arp.rs index 45e0156f68..c94dc2ce24 100644 --- a/bindgen-tests/tests/expectations/tests/layout_arp.rs +++ b/bindgen-tests/tests/expectations/tests/layout_arp.rs @@ -22,31 +22,14 @@ pub struct ether_addr { ///< Addr bytes in tx order pub addr_bytes: [u8; 6usize], } -#[test] -fn bindgen_test_layout_ether_addr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 6usize, - concat!("Size of: ", stringify!(ether_addr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ether_addr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).addr_bytes) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ether_addr), - "::", - stringify!(addr_bytes), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ether_addr"][::std::mem::size_of::() - 6usize]; + ["Alignment of ether_addr"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ether_addr::addr_bytes", + ][::std::mem::offset_of!(ether_addr, addr_bytes) - 0usize]; +}; /// ARP header IPv4 payload. #[repr(C, packed)] #[derive(Debug, Default, Copy, Clone)] @@ -60,41 +43,23 @@ pub struct arp_ipv4 { ///< target IP address pub arp_tip: u32, } -#[test] -fn bindgen_test_layout_arp_ipv4() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 20usize, - concat!("Size of: ", stringify!(arp_ipv4)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(arp_ipv4)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_sha) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(arp_ipv4), "::", stringify!(arp_sha)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_sip) as usize - ptr as usize }, - 6usize, - concat!("Offset of field: ", stringify!(arp_ipv4), "::", stringify!(arp_sip)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_tha) as usize - ptr as usize }, - 10usize, - concat!("Offset of field: ", stringify!(arp_ipv4), "::", stringify!(arp_tha)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_tip) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(arp_ipv4), "::", stringify!(arp_tip)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of arp_ipv4"][::std::mem::size_of::() - 20usize]; + ["Alignment of arp_ipv4"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: arp_ipv4::arp_sha", + ][::std::mem::offset_of!(arp_ipv4, arp_sha) - 0usize]; + [ + "Offset of field: arp_ipv4::arp_sip", + ][::std::mem::offset_of!(arp_ipv4, arp_sip) - 6usize]; + [ + "Offset of field: arp_ipv4::arp_tha", + ][::std::mem::offset_of!(arp_ipv4, arp_tha) - 10usize]; + [ + "Offset of field: arp_ipv4::arp_tip", + ][::std::mem::offset_of!(arp_ipv4, arp_tip) - 16usize]; +}; /// ARP header. #[repr(C, packed)] #[derive(Debug, Default, Copy, Clone)] @@ -106,48 +71,26 @@ pub struct arp_hdr { pub arp_op: u16, pub arp_data: arp_ipv4, } -#[test] -fn bindgen_test_layout_arp_hdr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 28usize, - concat!("Size of: ", stringify!(arp_hdr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(arp_hdr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_hrd) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(arp_hdr), "::", stringify!(arp_hrd)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_pro) as usize - ptr as usize }, - 2usize, - concat!("Offset of field: ", stringify!(arp_hdr), "::", stringify!(arp_pro)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_hln) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(arp_hdr), "::", stringify!(arp_hln)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_pln) as usize - ptr as usize }, - 5usize, - concat!("Offset of field: ", stringify!(arp_hdr), "::", stringify!(arp_pln)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_op) as usize - ptr as usize }, - 6usize, - concat!("Offset of field: ", stringify!(arp_hdr), "::", stringify!(arp_op)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arp_data) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(arp_hdr), "::", stringify!(arp_data)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of arp_hdr"][::std::mem::size_of::() - 28usize]; + ["Alignment of arp_hdr"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: arp_hdr::arp_hrd", + ][::std::mem::offset_of!(arp_hdr, arp_hrd) - 0usize]; + [ + "Offset of field: arp_hdr::arp_pro", + ][::std::mem::offset_of!(arp_hdr, arp_pro) - 2usize]; + [ + "Offset of field: arp_hdr::arp_hln", + ][::std::mem::offset_of!(arp_hdr, arp_hln) - 4usize]; + [ + "Offset of field: arp_hdr::arp_pln", + ][::std::mem::offset_of!(arp_hdr, arp_pln) - 5usize]; + [ + "Offset of field: arp_hdr::arp_op", + ][::std::mem::offset_of!(arp_hdr, arp_op) - 6usize]; + [ + "Offset of field: arp_hdr::arp_data", + ][::std::mem::offset_of!(arp_hdr, arp_data) - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/layout_array.rs b/bindgen-tests/tests/expectations/tests/layout_array.rs index dcf6f17b5c..b910159beb 100644 --- a/bindgen-tests/tests/expectations/tests/layout_array.rs +++ b/bindgen-tests/tests/expectations/tests/layout_array.rs @@ -68,62 +68,42 @@ fn bindgen_test_layout_rte_mempool_ops() { assert_eq!( ::std::mem::size_of::(), 128usize, - concat!("Size of: ", stringify!(rte_mempool_ops)), + "Size of rte_mempool_ops", ); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(rte_mempool_ops)), + "Alignment of rte_mempool_ops", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).name) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(rte_mempool_ops), "::", stringify!(name)), + "Offset of field: rte_mempool_ops::name", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).alloc) as usize - ptr as usize }, 32usize, - concat!( - "Offset of field: ", - stringify!(rte_mempool_ops), - "::", - stringify!(alloc), - ), + "Offset of field: rte_mempool_ops::alloc", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).free) as usize - ptr as usize }, 40usize, - concat!("Offset of field: ", stringify!(rte_mempool_ops), "::", stringify!(free)), + "Offset of field: rte_mempool_ops::free", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).enqueue) as usize - ptr as usize }, 48usize, - concat!( - "Offset of field: ", - stringify!(rte_mempool_ops), - "::", - stringify!(enqueue), - ), + "Offset of field: rte_mempool_ops::enqueue", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dequeue) as usize - ptr as usize }, 56usize, - concat!( - "Offset of field: ", - stringify!(rte_mempool_ops), - "::", - stringify!(dequeue), - ), + "Offset of field: rte_mempool_ops::dequeue", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).get_count) as usize - ptr as usize }, 64usize, - concat!( - "Offset of field: ", - stringify!(rte_mempool_ops), - "::", - stringify!(get_count), - ), + "Offset of field: rte_mempool_ops::get_count", ); } impl Default for rte_mempool_ops { @@ -156,22 +136,17 @@ fn bindgen_test_layout_rte_spinlock_t() { assert_eq!( ::std::mem::size_of::(), 4usize, - concat!("Size of: ", stringify!(rte_spinlock_t)), + "Size of rte_spinlock_t", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_spinlock_t)), + "Alignment of rte_spinlock_t", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).locked) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_spinlock_t), - "::", - stringify!(locked), - ), + "Offset of field: rte_spinlock_t::locked", ); } /** Structure storing the table of registered ops structs, each of which contain @@ -200,42 +175,27 @@ fn bindgen_test_layout_rte_mempool_ops_table() { assert_eq!( ::std::mem::size_of::(), 2112usize, - concat!("Size of: ", stringify!(rte_mempool_ops_table)), + "Size of rte_mempool_ops_table", ); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(rte_mempool_ops_table)), + "Alignment of rte_mempool_ops_table", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).sl) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mempool_ops_table), - "::", - stringify!(sl), - ), + "Offset of field: rte_mempool_ops_table::sl", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).num_ops) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_mempool_ops_table), - "::", - stringify!(num_ops), - ), + "Offset of field: rte_mempool_ops_table::num_ops", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).ops) as usize - ptr as usize }, 64usize, - concat!( - "Offset of field: ", - stringify!(rte_mempool_ops_table), - "::", - stringify!(ops), - ), + "Offset of field: rte_mempool_ops_table::ops", ); } impl Default for rte_mempool_ops_table { @@ -269,22 +229,17 @@ fn bindgen_test_layout_malloc_heap__bindgen_ty_1() { assert_eq!( ::std::mem::size_of::(), 8usize, - concat!("Size of: ", stringify!(malloc_heap__bindgen_ty_1)), + "Size of malloc_heap__bindgen_ty_1", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(malloc_heap__bindgen_ty_1)), + "Alignment of malloc_heap__bindgen_ty_1", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).lh_first) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(malloc_heap__bindgen_ty_1), - "::", - stringify!(lh_first), - ), + "Offset of field: malloc_heap__bindgen_ty_1::lh_first", ); } impl Default for malloc_heap__bindgen_ty_1 { @@ -300,50 +255,31 @@ impl Default for malloc_heap__bindgen_ty_1 { fn bindgen_test_layout_malloc_heap() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 128usize, - concat!("Size of: ", stringify!(malloc_heap)), - ); + assert_eq!(::std::mem::size_of::(), 128usize, "Size of malloc_heap"); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(malloc_heap)), + "Alignment of malloc_heap", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).lock) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(malloc_heap), "::", stringify!(lock)), + "Offset of field: malloc_heap::lock", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).free_head) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(malloc_heap), - "::", - stringify!(free_head), - ), + "Offset of field: malloc_heap::free_head", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).alloc_count) as usize - ptr as usize }, 112usize, - concat!( - "Offset of field: ", - stringify!(malloc_heap), - "::", - stringify!(alloc_count), - ), + "Offset of field: malloc_heap::alloc_count", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).total_size) as usize - ptr as usize }, 120usize, - concat!( - "Offset of field: ", - stringify!(malloc_heap), - "::", - stringify!(total_size), - ), + "Offset of field: malloc_heap::total_size", ); } impl Default for malloc_heap { diff --git a/bindgen-tests/tests/expectations/tests/layout_array_too_long.rs b/bindgen-tests/tests/expectations/tests/layout_array_too_long.rs index 52e7532ba2..d6ce2883d7 100644 --- a/bindgen-tests/tests/expectations/tests/layout_array_too_long.rs +++ b/bindgen-tests/tests/expectations/tests/layout_array_too_long.rs @@ -31,30 +31,22 @@ pub struct ip_frag { fn bindgen_test_layout_ip_frag() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(ip_frag)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ip_frag)), - ); + assert_eq!(::std::mem::size_of::(), 16usize, "Size of ip_frag"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of ip_frag"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).ofs) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(ip_frag), "::", stringify!(ofs)), + "Offset of field: ip_frag::ofs", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).len) as usize - ptr as usize }, 2usize, - concat!("Offset of field: ", stringify!(ip_frag), "::", stringify!(len)), + "Offset of field: ip_frag::len", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mb) as usize - ptr as usize }, 8usize, - concat!("Offset of field: ", stringify!(ip_frag), "::", stringify!(mb)), + "Offset of field: ip_frag::mb", ); } impl Default for ip_frag { @@ -81,30 +73,26 @@ pub struct ip_frag_key { fn bindgen_test_layout_ip_frag_key() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 40usize, - concat!("Size of: ", stringify!(ip_frag_key)), - ); + assert_eq!(::std::mem::size_of::(), 40usize, "Size of ip_frag_key"); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(ip_frag_key)), + "Alignment of ip_frag_key", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).src_dst) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(ip_frag_key), "::", stringify!(src_dst)), + "Offset of field: ip_frag_key::src_dst", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).id) as usize - ptr as usize }, 32usize, - concat!("Offset of field: ", stringify!(ip_frag_key), "::", stringify!(id)), + "Offset of field: ip_frag_key::id", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).key_len) as usize - ptr as usize }, 36usize, - concat!("Offset of field: ", stringify!(ip_frag_key), "::", stringify!(key_len)), + "Offset of field: ip_frag_key::key_len", ); } /** @internal Fragmented packet to reassemble. @@ -141,32 +129,22 @@ fn bindgen_test_layout_ip_frag_pkt__bindgen_ty_1() { assert_eq!( ::std::mem::size_of::(), 16usize, - concat!("Size of: ", stringify!(ip_frag_pkt__bindgen_ty_1)), + "Size of ip_frag_pkt__bindgen_ty_1", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(ip_frag_pkt__bindgen_ty_1)), + "Alignment of ip_frag_pkt__bindgen_ty_1", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tqe_next) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_pkt__bindgen_ty_1), - "::", - stringify!(tqe_next), - ), + "Offset of field: ip_frag_pkt__bindgen_ty_1::tqe_next", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tqe_prev) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_pkt__bindgen_ty_1), - "::", - stringify!(tqe_prev), - ), + "Offset of field: ip_frag_pkt__bindgen_ty_1::tqe_prev", ); } impl Default for ip_frag_pkt__bindgen_ty_1 { @@ -182,60 +160,46 @@ impl Default for ip_frag_pkt__bindgen_ty_1 { fn bindgen_test_layout_ip_frag_pkt() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 192usize, - concat!("Size of: ", stringify!(ip_frag_pkt)), - ); + assert_eq!(::std::mem::size_of::(), 192usize, "Size of ip_frag_pkt"); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(ip_frag_pkt)), + "Alignment of ip_frag_pkt", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).lru) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(lru)), + "Offset of field: ip_frag_pkt::lru", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).key) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(key)), + "Offset of field: ip_frag_pkt::key", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).start) as usize - ptr as usize }, 56usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(start)), + "Offset of field: ip_frag_pkt::start", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).total_size) as usize - ptr as usize }, 64usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_pkt), - "::", - stringify!(total_size), - ), + "Offset of field: ip_frag_pkt::total_size", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).frag_size) as usize - ptr as usize }, 68usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_pkt), - "::", - stringify!(frag_size), - ), + "Offset of field: ip_frag_pkt::frag_size", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).last_idx) as usize - ptr as usize }, 72usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(last_idx)), + "Offset of field: ip_frag_pkt::last_idx", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).frags) as usize - ptr as usize }, 80usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(frags)), + "Offset of field: ip_frag_pkt::frags", ); } impl Default for ip_frag_pkt { diff --git a/bindgen-tests/tests/expectations/tests/layout_cmdline_token.rs b/bindgen-tests/tests/expectations/tests/layout_cmdline_token.rs index 6141ab8f67..fb7b3bf584 100644 --- a/bindgen-tests/tests/expectations/tests/layout_cmdline_token.rs +++ b/bindgen-tests/tests/expectations/tests/layout_cmdline_token.rs @@ -7,41 +7,19 @@ pub struct cmdline_token_hdr { pub ops: *mut cmdline_token_ops, pub offset: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_cmdline_token_hdr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(cmdline_token_hdr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(cmdline_token_hdr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ops) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_hdr), - "::", - stringify!(ops), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).offset) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_hdr), - "::", - stringify!(offset), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of cmdline_token_hdr"][::std::mem::size_of::() - 16usize]; + [ + "Alignment of cmdline_token_hdr", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: cmdline_token_hdr::ops", + ][::std::mem::offset_of!(cmdline_token_hdr, ops) - 0usize]; + [ + "Offset of field: cmdline_token_hdr::offset", + ][::std::mem::offset_of!(cmdline_token_hdr, offset) - 8usize]; +}; impl Default for cmdline_token_hdr { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -107,61 +85,25 @@ pub struct cmdline_token_ops { ) -> ::std::os::raw::c_int, >, } -#[test] -fn bindgen_test_layout_cmdline_token_ops() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 32usize, - concat!("Size of: ", stringify!(cmdline_token_ops)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(cmdline_token_ops)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).parse) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_ops), - "::", - stringify!(parse), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).complete_get_nb) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_ops), - "::", - stringify!(complete_get_nb), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).complete_get_elt) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_ops), - "::", - stringify!(complete_get_elt), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).get_help) as usize - ptr as usize }, - 24usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_ops), - "::", - stringify!(get_help), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of cmdline_token_ops"][::std::mem::size_of::() - 32usize]; + [ + "Alignment of cmdline_token_ops", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: cmdline_token_ops::parse", + ][::std::mem::offset_of!(cmdline_token_ops, parse) - 0usize]; + [ + "Offset of field: cmdline_token_ops::complete_get_nb", + ][::std::mem::offset_of!(cmdline_token_ops, complete_get_nb) - 8usize]; + [ + "Offset of field: cmdline_token_ops::complete_get_elt", + ][::std::mem::offset_of!(cmdline_token_ops, complete_get_elt) - 16usize]; + [ + "Offset of field: cmdline_token_ops::get_help", + ][::std::mem::offset_of!(cmdline_token_ops, get_help) - 24usize]; +}; #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum cmdline_numtype { @@ -179,31 +121,18 @@ pub enum cmdline_numtype { pub struct cmdline_token_num_data { pub type_: cmdline_numtype, } -#[test] -fn bindgen_test_layout_cmdline_token_num_data() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(cmdline_token_num_data)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(cmdline_token_num_data)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).type_) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_num_data), - "::", - stringify!(type_), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of cmdline_token_num_data", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of cmdline_token_num_data", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: cmdline_token_num_data::type_", + ][::std::mem::offset_of!(cmdline_token_num_data, type_) - 0usize]; +}; impl Default for cmdline_token_num_data { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -219,41 +148,19 @@ pub struct cmdline_token_num { pub hdr: cmdline_token_hdr, pub num_data: cmdline_token_num_data, } -#[test] -fn bindgen_test_layout_cmdline_token_num() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(cmdline_token_num)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(cmdline_token_num)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hdr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_num), - "::", - stringify!(hdr), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).num_data) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(cmdline_token_num), - "::", - stringify!(num_data), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of cmdline_token_num"][::std::mem::size_of::() - 24usize]; + [ + "Alignment of cmdline_token_num", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: cmdline_token_num::hdr", + ][::std::mem::offset_of!(cmdline_token_num, hdr) - 0usize]; + [ + "Offset of field: cmdline_token_num::num_data", + ][::std::mem::offset_of!(cmdline_token_num, num_data) - 16usize]; +}; impl Default for cmdline_token_num { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/layout_eth_conf.rs b/bindgen-tests/tests/expectations/tests/layout_eth_conf.rs index 84af546c8c..4a62ddbea3 100644 --- a/bindgen-tests/tests/expectations/tests/layout_eth_conf.rs +++ b/bindgen-tests/tests/expectations/tests/layout_eth_conf.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,28 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -157,42 +161,27 @@ fn bindgen_test_layout_rte_eth_rxmode() { assert_eq!( ::std::mem::size_of::(), 12usize, - concat!("Size of: ", stringify!(rte_eth_rxmode)), + "Size of rte_eth_rxmode", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_rxmode)), + "Alignment of rte_eth_rxmode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mq_mode) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rxmode), - "::", - stringify!(mq_mode), - ), + "Offset of field: rte_eth_rxmode::mq_mode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).max_rx_pkt_len) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rxmode), - "::", - stringify!(max_rx_pkt_len), - ), + "Offset of field: rte_eth_rxmode::max_rx_pkt_len", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).split_hdr_size) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rxmode), - "::", - stringify!(split_hdr_size), - ), + "Offset of field: rte_eth_rxmode::split_hdr_size", ); } impl Default for rte_eth_rxmode { @@ -447,27 +436,22 @@ fn bindgen_test_layout_rte_eth_txmode() { assert_eq!( ::std::mem::size_of::(), 8usize, - concat!("Size of: ", stringify!(rte_eth_txmode)), + "Size of rte_eth_txmode", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_txmode)), + "Alignment of rte_eth_txmode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mq_mode) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_txmode), - "::", - stringify!(mq_mode), - ), + "Offset of field: rte_eth_txmode::mq_mode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pvid) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(rte_eth_txmode), "::", stringify!(pvid)), + "Offset of field: rte_eth_txmode::pvid", ); } impl Default for rte_eth_txmode { @@ -588,42 +572,27 @@ fn bindgen_test_layout_rte_eth_rss_conf() { assert_eq!( ::std::mem::size_of::(), 24usize, - concat!("Size of: ", stringify!(rte_eth_rss_conf)), + "Size of rte_eth_rss_conf", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(rte_eth_rss_conf)), + "Alignment of rte_eth_rss_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).rss_key) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rss_conf), - "::", - stringify!(rss_key), - ), + "Offset of field: rte_eth_rss_conf::rss_key", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).rss_key_len) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rss_conf), - "::", - stringify!(rss_key_len), - ), + "Offset of field: rte_eth_rss_conf::rss_key_len", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).rss_hf) as usize - ptr as usize }, 16usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rss_conf), - "::", - stringify!(rss_hf), - ), + "Offset of field: rte_eth_rss_conf::rss_hf", ); } impl Default for rte_eth_rss_conf { @@ -698,32 +667,22 @@ fn bindgen_test_layout_rte_eth_vmdq_dcb_conf__bindgen_ty_1() { assert_eq!( ::std::mem::size_of::(), 16usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_dcb_conf__bindgen_ty_1)), + "Size of rte_eth_vmdq_dcb_conf__bindgen_ty_1", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_dcb_conf__bindgen_ty_1)), + "Alignment of rte_eth_vmdq_dcb_conf__bindgen_ty_1", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).vlan_id) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf__bindgen_ty_1), - "::", - stringify!(vlan_id), - ), + "Offset of field: rte_eth_vmdq_dcb_conf__bindgen_ty_1::vlan_id", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pools) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf__bindgen_ty_1), - "::", - stringify!(pools), - ), + "Offset of field: rte_eth_vmdq_dcb_conf__bindgen_ty_1::pools", ); } #[test] @@ -733,74 +692,44 @@ fn bindgen_test_layout_rte_eth_vmdq_dcb_conf() { assert_eq!( ::std::mem::size_of::(), 1040usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_dcb_conf)), + "Size of rte_eth_vmdq_dcb_conf", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_dcb_conf)), + "Alignment of rte_eth_vmdq_dcb_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_queue_pools) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(nb_queue_pools), - ), + "Offset of field: rte_eth_vmdq_dcb_conf::nb_queue_pools", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).enable_default_pool) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(enable_default_pool), - ), + "Offset of field: rte_eth_vmdq_dcb_conf::enable_default_pool", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).default_pool) as usize - ptr as usize }, 5usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(default_pool), - ), + "Offset of field: rte_eth_vmdq_dcb_conf::default_pool", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_pool_maps) as usize - ptr as usize }, 6usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(nb_pool_maps), - ), + "Offset of field: rte_eth_vmdq_dcb_conf::nb_pool_maps", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pool_map) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(pool_map), - ), + "Offset of field: rte_eth_vmdq_dcb_conf::pool_map", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dcb_tc) as usize - ptr as usize }, 1032usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(dcb_tc), - ), + "Offset of field: rte_eth_vmdq_dcb_conf::dcb_tc", ); } impl Default for rte_eth_vmdq_dcb_conf { @@ -827,32 +756,22 @@ fn bindgen_test_layout_rte_eth_dcb_rx_conf() { assert_eq!( ::std::mem::size_of::(), 12usize, - concat!("Size of: ", stringify!(rte_eth_dcb_rx_conf)), + "Size of rte_eth_dcb_rx_conf", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_dcb_rx_conf)), + "Alignment of rte_eth_dcb_rx_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_tcs) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_dcb_rx_conf), - "::", - stringify!(nb_tcs), - ), + "Offset of field: rte_eth_dcb_rx_conf::nb_tcs", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dcb_tc) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_dcb_rx_conf), - "::", - stringify!(dcb_tc), - ), + "Offset of field: rte_eth_dcb_rx_conf::dcb_tc", ); } impl Default for rte_eth_dcb_rx_conf { @@ -879,32 +798,22 @@ fn bindgen_test_layout_rte_eth_vmdq_dcb_tx_conf() { assert_eq!( ::std::mem::size_of::(), 12usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_dcb_tx_conf)), + "Size of rte_eth_vmdq_dcb_tx_conf", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_dcb_tx_conf)), + "Alignment of rte_eth_vmdq_dcb_tx_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_queue_pools) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_tx_conf), - "::", - stringify!(nb_queue_pools), - ), + "Offset of field: rte_eth_vmdq_dcb_tx_conf::nb_queue_pools", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dcb_tc) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_tx_conf), - "::", - stringify!(dcb_tc), - ), + "Offset of field: rte_eth_vmdq_dcb_tx_conf::dcb_tc", ); } impl Default for rte_eth_vmdq_dcb_tx_conf { @@ -931,32 +840,22 @@ fn bindgen_test_layout_rte_eth_dcb_tx_conf() { assert_eq!( ::std::mem::size_of::(), 12usize, - concat!("Size of: ", stringify!(rte_eth_dcb_tx_conf)), + "Size of rte_eth_dcb_tx_conf", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_dcb_tx_conf)), + "Alignment of rte_eth_dcb_tx_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_tcs) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_dcb_tx_conf), - "::", - stringify!(nb_tcs), - ), + "Offset of field: rte_eth_dcb_tx_conf::nb_tcs", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dcb_tc) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_dcb_tx_conf), - "::", - stringify!(dcb_tc), - ), + "Offset of field: rte_eth_dcb_tx_conf::dcb_tc", ); } impl Default for rte_eth_dcb_tx_conf { @@ -981,22 +880,17 @@ fn bindgen_test_layout_rte_eth_vmdq_tx_conf() { assert_eq!( ::std::mem::size_of::(), 4usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_tx_conf)), + "Size of rte_eth_vmdq_tx_conf", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_tx_conf)), + "Alignment of rte_eth_vmdq_tx_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_queue_pools) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_tx_conf), - "::", - stringify!(nb_queue_pools), - ), + "Offset of field: rte_eth_vmdq_tx_conf::nb_queue_pools", ); } impl Default for rte_eth_vmdq_tx_conf { @@ -1041,32 +935,22 @@ fn bindgen_test_layout_rte_eth_vmdq_rx_conf__bindgen_ty_1() { assert_eq!( ::std::mem::size_of::(), 16usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_rx_conf__bindgen_ty_1)), + "Size of rte_eth_vmdq_rx_conf__bindgen_ty_1", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_rx_conf__bindgen_ty_1)), + "Alignment of rte_eth_vmdq_rx_conf__bindgen_ty_1", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).vlan_id) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf__bindgen_ty_1), - "::", - stringify!(vlan_id), - ), + "Offset of field: rte_eth_vmdq_rx_conf__bindgen_ty_1::vlan_id", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pools) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf__bindgen_ty_1), - "::", - stringify!(pools), - ), + "Offset of field: rte_eth_vmdq_rx_conf__bindgen_ty_1::pools", ); } #[test] @@ -1076,84 +960,49 @@ fn bindgen_test_layout_rte_eth_vmdq_rx_conf() { assert_eq!( ::std::mem::size_of::(), 1040usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_rx_conf)), + "Size of rte_eth_vmdq_rx_conf", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_rx_conf)), + "Alignment of rte_eth_vmdq_rx_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_queue_pools) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(nb_queue_pools), - ), + "Offset of field: rte_eth_vmdq_rx_conf::nb_queue_pools", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).enable_default_pool) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(enable_default_pool), - ), + "Offset of field: rte_eth_vmdq_rx_conf::enable_default_pool", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).default_pool) as usize - ptr as usize }, 5usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(default_pool), - ), + "Offset of field: rte_eth_vmdq_rx_conf::default_pool", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).enable_loop_back) as usize - ptr as usize }, 6usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(enable_loop_back), - ), + "Offset of field: rte_eth_vmdq_rx_conf::enable_loop_back", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_pool_maps) as usize - ptr as usize }, 7usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(nb_pool_maps), - ), + "Offset of field: rte_eth_vmdq_rx_conf::nb_pool_maps", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).rx_mode) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(rx_mode), - ), + "Offset of field: rte_eth_vmdq_rx_conf::rx_mode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pool_map) as usize - ptr as usize }, 16usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(pool_map), - ), + "Offset of field: rte_eth_vmdq_rx_conf::pool_map", ); } impl Default for rte_eth_vmdq_rx_conf { @@ -1225,62 +1074,37 @@ fn bindgen_test_layout_rte_eth_ipv4_flow() { assert_eq!( ::std::mem::size_of::(), 12usize, - concat!("Size of: ", stringify!(rte_eth_ipv4_flow)), + "Size of rte_eth_ipv4_flow", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_ipv4_flow)), + "Alignment of rte_eth_ipv4_flow", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).src_ip) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(src_ip), - ), + "Offset of field: rte_eth_ipv4_flow::src_ip", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dst_ip) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(dst_ip), - ), + "Offset of field: rte_eth_ipv4_flow::dst_ip", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tos) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(tos), - ), + "Offset of field: rte_eth_ipv4_flow::tos", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).ttl) as usize - ptr as usize }, 9usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(ttl), - ), + "Offset of field: rte_eth_ipv4_flow::ttl", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).proto) as usize - ptr as usize }, 10usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(proto), - ), + "Offset of field: rte_eth_ipv4_flow::proto", ); } /// A structure used to define the input for IPV6 flow @@ -1305,57 +1129,37 @@ fn bindgen_test_layout_rte_eth_ipv6_flow() { assert_eq!( ::std::mem::size_of::(), 36usize, - concat!("Size of: ", stringify!(rte_eth_ipv6_flow)), + "Size of rte_eth_ipv6_flow", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_ipv6_flow)), + "Alignment of rte_eth_ipv6_flow", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).src_ip) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv6_flow), - "::", - stringify!(src_ip), - ), + "Offset of field: rte_eth_ipv6_flow::src_ip", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dst_ip) as usize - ptr as usize }, 16usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv6_flow), - "::", - stringify!(dst_ip), - ), + "Offset of field: rte_eth_ipv6_flow::dst_ip", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tc) as usize - ptr as usize }, 32usize, - concat!("Offset of field: ", stringify!(rte_eth_ipv6_flow), "::", stringify!(tc)), + "Offset of field: rte_eth_ipv6_flow::tc", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).proto) as usize - ptr as usize }, 33usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv6_flow), - "::", - stringify!(proto), - ), + "Offset of field: rte_eth_ipv6_flow::proto", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).hop_limits) as usize - ptr as usize }, 34usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv6_flow), - "::", - stringify!(hop_limits), - ), + "Offset of field: rte_eth_ipv6_flow::hop_limits", ); } /** A structure used to configure FDIR masks that are used by the device @@ -1389,94 +1193,54 @@ fn bindgen_test_layout_rte_eth_fdir_masks() { assert_eq!( ::std::mem::size_of::(), 68usize, - concat!("Size of: ", stringify!(rte_eth_fdir_masks)), + "Size of rte_eth_fdir_masks", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_fdir_masks)), + "Alignment of rte_eth_fdir_masks", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).vlan_tci_mask) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(vlan_tci_mask), - ), + "Offset of field: rte_eth_fdir_masks::vlan_tci_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).ipv4_mask) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(ipv4_mask), - ), + "Offset of field: rte_eth_fdir_masks::ipv4_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).ipv6_mask) as usize - ptr as usize }, 16usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(ipv6_mask), - ), + "Offset of field: rte_eth_fdir_masks::ipv6_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).src_port_mask) as usize - ptr as usize }, 52usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(src_port_mask), - ), + "Offset of field: rte_eth_fdir_masks::src_port_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dst_port_mask) as usize - ptr as usize }, 54usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(dst_port_mask), - ), + "Offset of field: rte_eth_fdir_masks::dst_port_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mac_addr_byte_mask) as usize - ptr as usize }, 56usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(mac_addr_byte_mask), - ), + "Offset of field: rte_eth_fdir_masks::mac_addr_byte_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tunnel_id_mask) as usize - ptr as usize }, 60usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(tunnel_id_mask), - ), + "Offset of field: rte_eth_fdir_masks::tunnel_id_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tunnel_type_mask) as usize - ptr as usize }, 64usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(tunnel_type_mask), - ), + "Offset of field: rte_eth_fdir_masks::tunnel_type_mask", ); } #[repr(u32)] @@ -1506,32 +1270,22 @@ fn bindgen_test_layout_rte_eth_flex_payload_cfg() { assert_eq!( ::std::mem::size_of::(), 36usize, - concat!("Size of: ", stringify!(rte_eth_flex_payload_cfg)), + "Size of rte_eth_flex_payload_cfg", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_flex_payload_cfg)), + "Alignment of rte_eth_flex_payload_cfg", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).type_) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_flex_payload_cfg), - "::", - stringify!(type_), - ), + "Offset of field: rte_eth_flex_payload_cfg::type_", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).src_offset) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_flex_payload_cfg), - "::", - stringify!(src_offset), - ), + "Offset of field: rte_eth_flex_payload_cfg::src_offset", ); } impl Default for rte_eth_flex_payload_cfg { @@ -1558,32 +1312,22 @@ fn bindgen_test_layout_rte_eth_fdir_flex_mask() { assert_eq!( ::std::mem::size_of::(), 18usize, - concat!("Size of: ", stringify!(rte_eth_fdir_flex_mask)), + "Size of rte_eth_fdir_flex_mask", ); assert_eq!( ::std::mem::align_of::(), 2usize, - concat!("Alignment of ", stringify!(rte_eth_fdir_flex_mask)), + "Alignment of rte_eth_fdir_flex_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).flow_type) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_mask), - "::", - stringify!(flow_type), - ), + "Offset of field: rte_eth_fdir_flex_mask::flow_type", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mask) as usize - ptr as usize }, 2usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_mask), - "::", - stringify!(mask), - ), + "Offset of field: rte_eth_fdir_flex_mask::mask", ); } /** A structure used to define all flexible payload related setting @@ -1605,52 +1349,32 @@ fn bindgen_test_layout_rte_eth_fdir_flex_conf() { assert_eq!( ::std::mem::size_of::(), 688usize, - concat!("Size of: ", stringify!(rte_eth_fdir_flex_conf)), + "Size of rte_eth_fdir_flex_conf", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_fdir_flex_conf)), + "Alignment of rte_eth_fdir_flex_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_payloads) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_conf), - "::", - stringify!(nb_payloads), - ), + "Offset of field: rte_eth_fdir_flex_conf::nb_payloads", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_flexmasks) as usize - ptr as usize }, 2usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_conf), - "::", - stringify!(nb_flexmasks), - ), + "Offset of field: rte_eth_fdir_flex_conf::nb_flexmasks", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).flex_set) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_conf), - "::", - stringify!(flex_set), - ), + "Offset of field: rte_eth_fdir_flex_conf::flex_set", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).flex_mask) as usize - ptr as usize }, 292usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_conf), - "::", - stringify!(flex_mask), - ), + "Offset of field: rte_eth_fdir_flex_conf::flex_mask", ); } impl Default for rte_eth_fdir_flex_conf { @@ -1687,57 +1411,42 @@ fn bindgen_test_layout_rte_fdir_conf() { assert_eq!( ::std::mem::size_of::(), 772usize, - concat!("Size of: ", stringify!(rte_fdir_conf)), + "Size of rte_fdir_conf", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_fdir_conf)), + "Alignment of rte_fdir_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mode) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(rte_fdir_conf), "::", stringify!(mode)), + "Offset of field: rte_fdir_conf::mode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pballoc) as usize - ptr as usize }, 4usize, - concat!( - "Offset of field: ", - stringify!(rte_fdir_conf), - "::", - stringify!(pballoc), - ), + "Offset of field: rte_fdir_conf::pballoc", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).status) as usize - ptr as usize }, 8usize, - concat!("Offset of field: ", stringify!(rte_fdir_conf), "::", stringify!(status)), + "Offset of field: rte_fdir_conf::status", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).drop_queue) as usize - ptr as usize }, 12usize, - concat!( - "Offset of field: ", - stringify!(rte_fdir_conf), - "::", - stringify!(drop_queue), - ), + "Offset of field: rte_fdir_conf::drop_queue", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mask) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(rte_fdir_conf), "::", stringify!(mask)), + "Offset of field: rte_fdir_conf::mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).flex_conf) as usize - ptr as usize }, 84usize, - concat!( - "Offset of field: ", - stringify!(rte_fdir_conf), - "::", - stringify!(flex_conf), - ), + "Offset of field: rte_fdir_conf::flex_conf", ); } impl Default for rte_fdir_conf { @@ -1762,25 +1471,21 @@ pub struct rte_intr_conf { fn bindgen_test_layout_rte_intr_conf() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_intr_conf)), - ); + assert_eq!(::std::mem::size_of::(), 4usize, "Size of rte_intr_conf"); assert_eq!( ::std::mem::align_of::(), 2usize, - concat!("Alignment of ", stringify!(rte_intr_conf)), + "Alignment of rte_intr_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).lsc) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(rte_intr_conf), "::", stringify!(lsc)), + "Offset of field: rte_intr_conf::lsc", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).rxq) as usize - ptr as usize }, 2usize, - concat!("Offset of field: ", stringify!(rte_intr_conf), "::", stringify!(rxq)), + "Offset of field: rte_intr_conf::rxq", ); } /** A structure used to configure an Ethernet port. @@ -1835,52 +1540,32 @@ fn bindgen_test_layout_rte_eth_conf__bindgen_ty_1() { assert_eq!( ::std::mem::size_of::(), 2120usize, - concat!("Size of: ", stringify!(rte_eth_conf__bindgen_ty_1)), + "Size of rte_eth_conf__bindgen_ty_1", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(rte_eth_conf__bindgen_ty_1)), + "Alignment of rte_eth_conf__bindgen_ty_1", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).rss_conf) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_1), - "::", - stringify!(rss_conf), - ), + "Offset of field: rte_eth_conf__bindgen_ty_1::rss_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).vmdq_dcb_conf) as usize - ptr as usize }, 24usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_1), - "::", - stringify!(vmdq_dcb_conf), - ), + "Offset of field: rte_eth_conf__bindgen_ty_1::vmdq_dcb_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dcb_rx_conf) as usize - ptr as usize }, 1064usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_1), - "::", - stringify!(dcb_rx_conf), - ), + "Offset of field: rte_eth_conf__bindgen_ty_1::dcb_rx_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).vmdq_rx_conf) as usize - ptr as usize }, 1080usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_1), - "::", - stringify!(vmdq_rx_conf), - ), + "Offset of field: rte_eth_conf__bindgen_ty_1::vmdq_rx_conf", ); } impl Default for rte_eth_conf__bindgen_ty_1 { @@ -1906,42 +1591,27 @@ fn bindgen_test_layout_rte_eth_conf__bindgen_ty_2() { assert_eq!( ::std::mem::size_of::(), 12usize, - concat!("Size of: ", stringify!(rte_eth_conf__bindgen_ty_2)), + "Size of rte_eth_conf__bindgen_ty_2", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(rte_eth_conf__bindgen_ty_2)), + "Alignment of rte_eth_conf__bindgen_ty_2", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).vmdq_dcb_tx_conf) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_2), - "::", - stringify!(vmdq_dcb_tx_conf), - ), + "Offset of field: rte_eth_conf__bindgen_ty_2::vmdq_dcb_tx_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dcb_tx_conf) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_2), - "::", - stringify!(dcb_tx_conf), - ), + "Offset of field: rte_eth_conf__bindgen_ty_2::dcb_tx_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).vmdq_tx_conf) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_2), - "::", - stringify!(vmdq_tx_conf), - ), + "Offset of field: rte_eth_conf__bindgen_ty_2::vmdq_tx_conf", ); } impl Default for rte_eth_conf__bindgen_ty_2 { @@ -1957,97 +1627,58 @@ impl Default for rte_eth_conf__bindgen_ty_2 { fn bindgen_test_layout_rte_eth_conf() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2944usize, - concat!("Size of: ", stringify!(rte_eth_conf)), - ); + assert_eq!(::std::mem::size_of::(), 2944usize, "Size of rte_eth_conf"); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(rte_eth_conf)), + "Alignment of rte_eth_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).link_speeds) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(link_speeds), - ), + "Offset of field: rte_eth_conf::link_speeds", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).rxmode) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(rte_eth_conf), "::", stringify!(rxmode)), + "Offset of field: rte_eth_conf::rxmode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).txmode) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(rte_eth_conf), "::", stringify!(txmode)), + "Offset of field: rte_eth_conf::txmode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).lpbk_mode) as usize - ptr as usize }, 24usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(lpbk_mode), - ), + "Offset of field: rte_eth_conf::lpbk_mode", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).rx_adv_conf) as usize - ptr as usize }, 32usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(rx_adv_conf), - ), + "Offset of field: rte_eth_conf::rx_adv_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tx_adv_conf) as usize - ptr as usize }, 2152usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(tx_adv_conf), - ), + "Offset of field: rte_eth_conf::tx_adv_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).dcb_capability_en) as usize - ptr as usize }, 2164usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(dcb_capability_en), - ), + "Offset of field: rte_eth_conf::dcb_capability_en", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).fdir_conf) as usize - ptr as usize }, 2168usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(fdir_conf), - ), + "Offset of field: rte_eth_conf::fdir_conf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).intr_conf) as usize - ptr as usize }, 2940usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(intr_conf), - ), + "Offset of field: rte_eth_conf::intr_conf", ); } impl Default for rte_eth_conf { diff --git a/bindgen-tests/tests/expectations/tests/layout_eth_conf_1_0.rs b/bindgen-tests/tests/expectations/tests/layout_eth_conf_1_0.rs deleted file mode 100644 index e2ae2b0c17..0000000000 --- a/bindgen-tests/tests/expectations/tests/layout_eth_conf_1_0.rs +++ /dev/null @@ -1,2206 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub struct __BindgenBitfieldUnit { - storage: Storage, -} -impl __BindgenBitfieldUnit { - #[inline] - pub fn new(storage: Storage) -> Self { - Self { storage } - } -} -impl __BindgenBitfieldUnit -where - Storage: AsRef<[u8]> + AsMut<[u8]>, -{ - #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - byte & mask == mask - } - #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } - } - #[inline] - pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - let mut val = 0; - for i in 0..(bit_width as usize) { - if self.get_bit(i + bit_offset) { - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - val |= 1 << index; - } - } - val - } - #[inline] - pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - for i in 0..(bit_width as usize) { - let mask = 1 << i; - let val_bit_is_set = val & mask == mask; - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - self.set_bit(index + bit_offset, val_bit_is_set); - } - } -} -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -pub const ETH_MQ_RX_RSS_FLAG: u32 = 1; -pub const ETH_MQ_RX_DCB_FLAG: u32 = 2; -pub const ETH_MQ_RX_VMDQ_FLAG: u32 = 4; -pub const ETH_VMDQ_MAX_VLAN_FILTERS: u32 = 64; -pub const ETH_DCB_NUM_USER_PRIORITIES: u32 = 8; -pub const ETH_VMDQ_DCB_NUM_QUEUES: u32 = 128; -pub const ETH_DCB_NUM_QUEUES: u32 = 128; -pub const RTE_ETH_FDIR_MAX_FLEXLEN: u32 = 16; -pub const RTE_ETH_INSET_SIZE_MAX: u32 = 128; -pub const RTE_ETH_FLOW_UNKNOWN: u32 = 0; -pub const RTE_ETH_FLOW_RAW: u32 = 1; -pub const RTE_ETH_FLOW_IPV4: u32 = 2; -pub const RTE_ETH_FLOW_FRAG_IPV4: u32 = 3; -pub const RTE_ETH_FLOW_NONFRAG_IPV4_TCP: u32 = 4; -pub const RTE_ETH_FLOW_NONFRAG_IPV4_UDP: u32 = 5; -pub const RTE_ETH_FLOW_NONFRAG_IPV4_SCTP: u32 = 6; -pub const RTE_ETH_FLOW_NONFRAG_IPV4_OTHER: u32 = 7; -pub const RTE_ETH_FLOW_IPV6: u32 = 8; -pub const RTE_ETH_FLOW_FRAG_IPV6: u32 = 9; -pub const RTE_ETH_FLOW_NONFRAG_IPV6_TCP: u32 = 10; -pub const RTE_ETH_FLOW_NONFRAG_IPV6_UDP: u32 = 11; -pub const RTE_ETH_FLOW_NONFRAG_IPV6_SCTP: u32 = 12; -pub const RTE_ETH_FLOW_NONFRAG_IPV6_OTHER: u32 = 13; -pub const RTE_ETH_FLOW_L2_PAYLOAD: u32 = 14; -pub const RTE_ETH_FLOW_IPV6_EX: u32 = 15; -pub const RTE_ETH_FLOW_IPV6_TCP_EX: u32 = 16; -pub const RTE_ETH_FLOW_IPV6_UDP_EX: u32 = 17; -pub const RTE_ETH_FLOW_PORT: u32 = 18; -pub const RTE_ETH_FLOW_VXLAN: u32 = 19; -pub const RTE_ETH_FLOW_GENEVE: u32 = 20; -pub const RTE_ETH_FLOW_NVGRE: u32 = 21; -pub const RTE_ETH_FLOW_MAX: u32 = 22; -#[repr(u32)] -/** A set of values to identify what method is to be used to route - packets to multiple queues.*/ -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum rte_eth_rx_mq_mode { - /// None of DCB,RSS or VMDQ mode - ETH_MQ_RX_NONE = 0, - /// For RX side, only RSS is on - ETH_MQ_RX_RSS = 1, - /// For RX side,only DCB is on. - ETH_MQ_RX_DCB = 2, - /// Both DCB and RSS enable - ETH_MQ_RX_DCB_RSS = 3, - /// Only VMDQ, no RSS nor DCB - ETH_MQ_RX_VMDQ_ONLY = 4, - /// RSS mode with VMDQ - ETH_MQ_RX_VMDQ_RSS = 5, - /// Use VMDQ+DCB to route traffic to queues - ETH_MQ_RX_VMDQ_DCB = 6, - /// Enable both VMDQ and DCB in VMDq - ETH_MQ_RX_VMDQ_DCB_RSS = 7, -} -/// A structure used to configure the RX features of an Ethernet port. -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_rxmode { - /// The multi-queue packet distribution mode to be used, e.g. RSS. - pub mq_mode: rte_eth_rx_mq_mode, - ///< Only used if jumbo_frame enabled. - pub max_rx_pkt_len: u32, - ///< hdr buf size (header_split enabled). - pub split_hdr_size: u16, - pub _bitfield_align_1: [u8; 0], - pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, -} -#[test] -fn bindgen_test_layout_rte_eth_rxmode() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rte_eth_rxmode)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_rxmode)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mq_mode) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rxmode), - "::", - stringify!(mq_mode), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).max_rx_pkt_len) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rxmode), - "::", - stringify!(max_rx_pkt_len), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).split_hdr_size) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rxmode), - "::", - stringify!(split_hdr_size), - ), - ); -} -impl Clone for rte_eth_rxmode { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_rxmode { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -impl rte_eth_rxmode { - #[inline] - pub fn header_split(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u16) } - } - #[inline] - pub fn set_header_split(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(0usize, 1u8, val as u64) - } - } - #[inline] - pub fn hw_ip_checksum(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u16) } - } - #[inline] - pub fn set_hw_ip_checksum(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(1usize, 1u8, val as u64) - } - } - #[inline] - pub fn hw_vlan_filter(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u16) } - } - #[inline] - pub fn set_hw_vlan_filter(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(2usize, 1u8, val as u64) - } - } - #[inline] - pub fn hw_vlan_strip(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u16) } - } - #[inline] - pub fn set_hw_vlan_strip(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(3usize, 1u8, val as u64) - } - } - #[inline] - pub fn hw_vlan_extend(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u16) } - } - #[inline] - pub fn set_hw_vlan_extend(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(4usize, 1u8, val as u64) - } - } - #[inline] - pub fn jumbo_frame(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u16) } - } - #[inline] - pub fn set_jumbo_frame(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(5usize, 1u8, val as u64) - } - } - #[inline] - pub fn hw_strip_crc(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u16) } - } - #[inline] - pub fn set_hw_strip_crc(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(6usize, 1u8, val as u64) - } - } - #[inline] - pub fn enable_scatter(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u16) } - } - #[inline] - pub fn set_enable_scatter(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(7usize, 1u8, val as u64) - } - } - #[inline] - pub fn enable_lro(&self) -> u16 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u16) } - } - #[inline] - pub fn set_enable_lro(&mut self, val: u16) { - unsafe { - let val: u16 = ::std::mem::transmute(val); - self._bitfield_1.set(8usize, 1u8, val as u64) - } - } - #[inline] - pub fn new_bitfield_1( - header_split: u16, - hw_ip_checksum: u16, - hw_vlan_filter: u16, - hw_vlan_strip: u16, - hw_vlan_extend: u16, - jumbo_frame: u16, - hw_strip_crc: u16, - enable_scatter: u16, - enable_lro: u16, - ) -> __BindgenBitfieldUnit<[u8; 2usize]> { - let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize]> = Default::default(); - __bindgen_bitfield_unit - .set( - 0usize, - 1u8, - { - let header_split: u16 = unsafe { - ::std::mem::transmute(header_split) - }; - header_split as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 1usize, - 1u8, - { - let hw_ip_checksum: u16 = unsafe { - ::std::mem::transmute(hw_ip_checksum) - }; - hw_ip_checksum as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 2usize, - 1u8, - { - let hw_vlan_filter: u16 = unsafe { - ::std::mem::transmute(hw_vlan_filter) - }; - hw_vlan_filter as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 3usize, - 1u8, - { - let hw_vlan_strip: u16 = unsafe { - ::std::mem::transmute(hw_vlan_strip) - }; - hw_vlan_strip as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 4usize, - 1u8, - { - let hw_vlan_extend: u16 = unsafe { - ::std::mem::transmute(hw_vlan_extend) - }; - hw_vlan_extend as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 5usize, - 1u8, - { - let jumbo_frame: u16 = unsafe { ::std::mem::transmute(jumbo_frame) }; - jumbo_frame as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 6usize, - 1u8, - { - let hw_strip_crc: u16 = unsafe { - ::std::mem::transmute(hw_strip_crc) - }; - hw_strip_crc as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 7usize, - 1u8, - { - let enable_scatter: u16 = unsafe { - ::std::mem::transmute(enable_scatter) - }; - enable_scatter as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 8usize, - 1u8, - { - let enable_lro: u16 = unsafe { ::std::mem::transmute(enable_lro) }; - enable_lro as u64 - }, - ); - __bindgen_bitfield_unit - } -} -#[repr(u32)] -/** A set of values to identify what method is to be used to transmit - packets using multi-TCs.*/ -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum rte_eth_tx_mq_mode { - ///< It is in neither DCB nor VT mode. - ETH_MQ_TX_NONE = 0, - ///< For TX side,only DCB is on. - ETH_MQ_TX_DCB = 1, - ///< For TX side,both DCB and VT is on. - ETH_MQ_TX_VMDQ_DCB = 2, - ///< Only VT on, no DCB - ETH_MQ_TX_VMDQ_ONLY = 3, -} -/// A structure used to configure the TX features of an Ethernet port. -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_txmode { - ///< TX multi-queues mode. - pub mq_mode: rte_eth_tx_mq_mode, - pub pvid: u16, - pub _bitfield_align_1: [u8; 0], - pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, - pub __bindgen_padding_0: u8, -} -#[test] -fn bindgen_test_layout_rte_eth_txmode() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_eth_txmode)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_txmode)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mq_mode) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_txmode), - "::", - stringify!(mq_mode), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pvid) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(rte_eth_txmode), "::", stringify!(pvid)), - ); -} -impl Clone for rte_eth_txmode { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_txmode { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -impl rte_eth_txmode { - #[inline] - pub fn hw_vlan_reject_tagged(&self) -> u8 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u8) } - } - #[inline] - pub fn set_hw_vlan_reject_tagged(&mut self, val: u8) { - unsafe { - let val: u8 = ::std::mem::transmute(val); - self._bitfield_1.set(0usize, 1u8, val as u64) - } - } - #[inline] - pub fn hw_vlan_reject_untagged(&self) -> u8 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u8) } - } - #[inline] - pub fn set_hw_vlan_reject_untagged(&mut self, val: u8) { - unsafe { - let val: u8 = ::std::mem::transmute(val); - self._bitfield_1.set(1usize, 1u8, val as u64) - } - } - #[inline] - pub fn hw_vlan_insert_pvid(&self) -> u8 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u8) } - } - #[inline] - pub fn set_hw_vlan_insert_pvid(&mut self, val: u8) { - unsafe { - let val: u8 = ::std::mem::transmute(val); - self._bitfield_1.set(2usize, 1u8, val as u64) - } - } - #[inline] - pub fn new_bitfield_1( - hw_vlan_reject_tagged: u8, - hw_vlan_reject_untagged: u8, - hw_vlan_insert_pvid: u8, - ) -> __BindgenBitfieldUnit<[u8; 1usize]> { - let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); - __bindgen_bitfield_unit - .set( - 0usize, - 1u8, - { - let hw_vlan_reject_tagged: u8 = unsafe { - ::std::mem::transmute(hw_vlan_reject_tagged) - }; - hw_vlan_reject_tagged as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 1usize, - 1u8, - { - let hw_vlan_reject_untagged: u8 = unsafe { - ::std::mem::transmute(hw_vlan_reject_untagged) - }; - hw_vlan_reject_untagged as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 2usize, - 1u8, - { - let hw_vlan_insert_pvid: u8 = unsafe { - ::std::mem::transmute(hw_vlan_insert_pvid) - }; - hw_vlan_insert_pvid as u64 - }, - ); - __bindgen_bitfield_unit - } -} -/** A structure used to configure the Receive Side Scaling (RSS) feature - of an Ethernet port. - If not NULL, the *rss_key* pointer of the *rss_conf* structure points - to an array holding the RSS key to use for hashing specific header - fields of received packets. The length of this array should be indicated - by *rss_key_len* below. Otherwise, a default random hash key is used by - the device driver. - - The *rss_key_len* field of the *rss_conf* structure indicates the length - in bytes of the array pointed by *rss_key*. To be compatible, this length - will be checked in i40e only. Others assume 40 bytes to be used as before. - - The *rss_hf* field of the *rss_conf* structure indicates the different - types of IPv4/IPv6 packets to which the RSS hashing must be applied. - Supplying an *rss_hf* equal to zero disables the RSS feature.*/ -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_rss_conf { - ///< If not NULL, 40-byte hash key. - pub rss_key: *mut u8, - ///< hash key length in bytes. - pub rss_key_len: u8, - ///< Hash functions to apply - see below. - pub rss_hf: u64, -} -#[test] -fn bindgen_test_layout_rte_eth_rss_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(rte_eth_rss_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_eth_rss_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rss_key) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rss_conf), - "::", - stringify!(rss_key), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rss_key_len) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rss_conf), - "::", - stringify!(rss_key_len), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rss_hf) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_rss_conf), - "::", - stringify!(rss_hf), - ), - ); -} -impl Clone for rte_eth_rss_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_rss_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(u32)] -/** This enum indicates the possible number of traffic classes - in DCB configratioins*/ -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum rte_eth_nb_tcs { - ///< 4 TCs with DCB. - ETH_4_TCS = 4, - ///< 8 TCs with DCB. - ETH_8_TCS = 8, -} -#[repr(u32)] -/** This enum indicates the possible number of queue pools - in VMDQ configurations.*/ -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum rte_eth_nb_pools { - ///< 8 VMDq pools. - ETH_8_POOLS = 8, - ///< 16 VMDq pools. - ETH_16_POOLS = 16, - ///< 32 VMDq pools. - ETH_32_POOLS = 32, - ///< 64 VMDq pools. - ETH_64_POOLS = 64, -} -/** A structure used to configure the VMDQ+DCB feature - of an Ethernet port. - - Using this feature, packets are routed to a pool of queues, based - on the vlan ID in the vlan tag, and then to a specific queue within - that pool, using the user priority vlan tag field. - - A default pool may be used, if desired, to route all traffic which - does not match the vlan filter rules.*/ -#[repr(C)] -#[derive(Copy)] -pub struct rte_eth_vmdq_dcb_conf { - ///< With DCB, 16 or 32 pools - pub nb_queue_pools: rte_eth_nb_pools, - ///< If non-zero, use a default pool - pub enable_default_pool: u8, - ///< The default pool, if applicable - pub default_pool: u8, - ///< We can have up to 64 filters/mappings - pub nb_pool_maps: u8, - ///< VMDq vlan pool maps. - pub pool_map: [rte_eth_vmdq_dcb_conf__bindgen_ty_1; 64usize], - pub dcb_tc: [u8; 8usize], -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_vmdq_dcb_conf__bindgen_ty_1 { - ///< The vlan ID of the received frame - pub vlan_id: u16, - ///< Bitmask of pools for packet rx - pub pools: u64, -} -#[test] -fn bindgen_test_layout_rte_eth_vmdq_dcb_conf__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_dcb_conf__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_dcb_conf__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vlan_id) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf__bindgen_ty_1), - "::", - stringify!(vlan_id), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pools) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf__bindgen_ty_1), - "::", - stringify!(pools), - ), - ); -} -impl Clone for rte_eth_vmdq_dcb_conf__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_eth_vmdq_dcb_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1040usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_dcb_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_dcb_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_queue_pools) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(nb_queue_pools), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).enable_default_pool) as usize - ptr as usize - }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(enable_default_pool), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).default_pool) as usize - ptr as usize }, - 5usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(default_pool), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_pool_maps) as usize - ptr as usize }, - 6usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(nb_pool_maps), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pool_map) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(pool_map), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dcb_tc) as usize - ptr as usize }, - 1032usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_conf), - "::", - stringify!(dcb_tc), - ), - ); -} -impl Clone for rte_eth_vmdq_dcb_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_vmdq_dcb_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_dcb_rx_conf { - ///< Possible DCB TCs, 4 or 8 TCs - pub nb_tcs: rte_eth_nb_tcs, - /// Traffic class each UP mapped to. - pub dcb_tc: [u8; 8usize], -} -#[test] -fn bindgen_test_layout_rte_eth_dcb_rx_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rte_eth_dcb_rx_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_dcb_rx_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_tcs) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_dcb_rx_conf), - "::", - stringify!(nb_tcs), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dcb_tc) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_dcb_rx_conf), - "::", - stringify!(dcb_tc), - ), - ); -} -impl Clone for rte_eth_dcb_rx_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_dcb_rx_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_vmdq_dcb_tx_conf { - ///< With DCB, 16 or 32 pools. - pub nb_queue_pools: rte_eth_nb_pools, - /// Traffic class each UP mapped to. - pub dcb_tc: [u8; 8usize], -} -#[test] -fn bindgen_test_layout_rte_eth_vmdq_dcb_tx_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_dcb_tx_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_dcb_tx_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_queue_pools) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_tx_conf), - "::", - stringify!(nb_queue_pools), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dcb_tc) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_dcb_tx_conf), - "::", - stringify!(dcb_tc), - ), - ); -} -impl Clone for rte_eth_vmdq_dcb_tx_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_vmdq_dcb_tx_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_dcb_tx_conf { - ///< Possible DCB TCs, 4 or 8 TCs. - pub nb_tcs: rte_eth_nb_tcs, - /// Traffic class each UP mapped to. - pub dcb_tc: [u8; 8usize], -} -#[test] -fn bindgen_test_layout_rte_eth_dcb_tx_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rte_eth_dcb_tx_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_dcb_tx_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_tcs) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_dcb_tx_conf), - "::", - stringify!(nb_tcs), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dcb_tc) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_dcb_tx_conf), - "::", - stringify!(dcb_tc), - ), - ); -} -impl Clone for rte_eth_dcb_tx_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_dcb_tx_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_vmdq_tx_conf { - ///< VMDq mode, 64 pools. - pub nb_queue_pools: rte_eth_nb_pools, -} -#[test] -fn bindgen_test_layout_rte_eth_vmdq_tx_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_tx_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_tx_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_queue_pools) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_tx_conf), - "::", - stringify!(nb_queue_pools), - ), - ); -} -impl Clone for rte_eth_vmdq_tx_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_vmdq_tx_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Copy)] -pub struct rte_eth_vmdq_rx_conf { - ///< VMDq only mode, 8 or 64 pools - pub nb_queue_pools: rte_eth_nb_pools, - ///< If non-zero, use a default pool - pub enable_default_pool: u8, - ///< The default pool, if applicable - pub default_pool: u8, - ///< Enable VT loop back - pub enable_loop_back: u8, - ///< We can have up to 64 filters/mappings - pub nb_pool_maps: u8, - ///< Flags from ETH_VMDQ_ACCEPT_* - pub rx_mode: u32, - ///< VMDq vlan pool maps. - pub pool_map: [rte_eth_vmdq_rx_conf__bindgen_ty_1; 64usize], -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_vmdq_rx_conf__bindgen_ty_1 { - ///< The vlan ID of the received frame - pub vlan_id: u16, - ///< Bitmask of pools for packet rx - pub pools: u64, -} -#[test] -fn bindgen_test_layout_rte_eth_vmdq_rx_conf__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_rx_conf__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_rx_conf__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vlan_id) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf__bindgen_ty_1), - "::", - stringify!(vlan_id), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pools) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf__bindgen_ty_1), - "::", - stringify!(pools), - ), - ); -} -impl Clone for rte_eth_vmdq_rx_conf__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_eth_vmdq_rx_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1040usize, - concat!("Size of: ", stringify!(rte_eth_vmdq_rx_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_eth_vmdq_rx_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_queue_pools) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(nb_queue_pools), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).enable_default_pool) as usize - ptr as usize - }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(enable_default_pool), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).default_pool) as usize - ptr as usize }, - 5usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(default_pool), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).enable_loop_back) as usize - ptr as usize }, - 6usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(enable_loop_back), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_pool_maps) as usize - ptr as usize }, - 7usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(nb_pool_maps), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rx_mode) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(rx_mode), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pool_map) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_vmdq_rx_conf), - "::", - stringify!(pool_map), - ), - ); -} -impl Clone for rte_eth_vmdq_rx_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_vmdq_rx_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(u32)] -/// Flow Director setting modes: none, signature or perfect. -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum rte_fdir_mode { - ///< Disable FDIR support. - RTE_FDIR_MODE_NONE = 0, - ///< Enable FDIR signature filter mode. - RTE_FDIR_MODE_SIGNATURE = 1, - ///< Enable FDIR perfect filter mode. - RTE_FDIR_MODE_PERFECT = 2, - ///< Enable FDIR filter mode - MAC VLAN. - RTE_FDIR_MODE_PERFECT_MAC_VLAN = 3, - ///< Enable FDIR filter mode - tunnel. - RTE_FDIR_MODE_PERFECT_TUNNEL = 4, -} -#[repr(u32)] -/** Memory space that can be configured to store Flow Director filters - in the board memory.*/ -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum rte_fdir_pballoc_type { - ///< 64k. - RTE_FDIR_PBALLOC_64K = 0, - ///< 128k. - RTE_FDIR_PBALLOC_128K = 1, - ///< 256k. - RTE_FDIR_PBALLOC_256K = 2, -} -#[repr(u32)] -/// Select report mode of FDIR hash information in RX descriptors. -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum rte_fdir_status_mode { - ///< Never report FDIR hash. - RTE_FDIR_NO_REPORT_STATUS = 0, - ///< Only report FDIR hash for matching pkts. - RTE_FDIR_REPORT_STATUS = 1, - ///< Always report FDIR hash. - RTE_FDIR_REPORT_STATUS_ALWAYS = 2, -} -/// A structure used to define the input for IPV4 flow -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_ipv4_flow { - ///< IPv4 source address in big endian. - pub src_ip: u32, - ///< IPv4 destination address in big endian. - pub dst_ip: u32, - ///< Type of service to match. - pub tos: u8, - ///< Time to live to match. - pub ttl: u8, - ///< Protocol, next header in big endian. - pub proto: u8, -} -#[test] -fn bindgen_test_layout_rte_eth_ipv4_flow() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rte_eth_ipv4_flow)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_ipv4_flow)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).src_ip) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(src_ip), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dst_ip) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(dst_ip), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tos) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(tos), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ttl) as usize - ptr as usize }, - 9usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(ttl), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).proto) as usize - ptr as usize }, - 10usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv4_flow), - "::", - stringify!(proto), - ), - ); -} -impl Clone for rte_eth_ipv4_flow { - fn clone(&self) -> Self { - *self - } -} -/// A structure used to define the input for IPV6 flow -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_ipv6_flow { - ///< IPv6 source address in big endian. - pub src_ip: [u32; 4usize], - ///< IPv6 destination address in big endian. - pub dst_ip: [u32; 4usize], - ///< Traffic class to match. - pub tc: u8, - ///< Protocol, next header to match. - pub proto: u8, - ///< Hop limits to match. - pub hop_limits: u8, -} -#[test] -fn bindgen_test_layout_rte_eth_ipv6_flow() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 36usize, - concat!("Size of: ", stringify!(rte_eth_ipv6_flow)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_ipv6_flow)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).src_ip) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv6_flow), - "::", - stringify!(src_ip), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dst_ip) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv6_flow), - "::", - stringify!(dst_ip), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tc) as usize - ptr as usize }, - 32usize, - concat!("Offset of field: ", stringify!(rte_eth_ipv6_flow), "::", stringify!(tc)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).proto) as usize - ptr as usize }, - 33usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv6_flow), - "::", - stringify!(proto), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hop_limits) as usize - ptr as usize }, - 34usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_ipv6_flow), - "::", - stringify!(hop_limits), - ), - ); -} -impl Clone for rte_eth_ipv6_flow { - fn clone(&self) -> Self { - *self - } -} -/** A structure used to configure FDIR masks that are used by the device - to match the various fields of RX packet headers.*/ -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_fdir_masks { - ///< Bit mask for vlan_tci in big endian - pub vlan_tci_mask: u16, - /// Bit mask for ipv4 flow in big endian. - pub ipv4_mask: rte_eth_ipv4_flow, - /// Bit maks for ipv6 flow in big endian. - pub ipv6_mask: rte_eth_ipv6_flow, - /// Bit mask for L4 source port in big endian. - pub src_port_mask: u16, - /// Bit mask for L4 destination port in big endian. - pub dst_port_mask: u16, - /** 6 bit mask for proper 6 bytes of Mac address, bit 0 matches the -first byte on the wire*/ - pub mac_addr_byte_mask: u8, - /// Bit mask for tunnel ID in big endian. - pub tunnel_id_mask: u32, - /**< 1 - Match tunnel type, -0 - Ignore tunnel type.*/ - pub tunnel_type_mask: u8, -} -#[test] -fn bindgen_test_layout_rte_eth_fdir_masks() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 68usize, - concat!("Size of: ", stringify!(rte_eth_fdir_masks)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_fdir_masks)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vlan_tci_mask) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(vlan_tci_mask), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ipv4_mask) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(ipv4_mask), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ipv6_mask) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(ipv6_mask), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).src_port_mask) as usize - ptr as usize }, - 52usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(src_port_mask), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dst_port_mask) as usize - ptr as usize }, - 54usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(dst_port_mask), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mac_addr_byte_mask) as usize - ptr as usize - }, - 56usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(mac_addr_byte_mask), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tunnel_id_mask) as usize - ptr as usize }, - 60usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(tunnel_id_mask), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tunnel_type_mask) as usize - ptr as usize }, - 64usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_masks), - "::", - stringify!(tunnel_type_mask), - ), - ); -} -impl Clone for rte_eth_fdir_masks { - fn clone(&self) -> Self { - *self - } -} -#[repr(u32)] -/// Payload type -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum rte_eth_payload_type { - RTE_ETH_PAYLOAD_UNKNOWN = 0, - RTE_ETH_RAW_PAYLOAD = 1, - RTE_ETH_L2_PAYLOAD = 2, - RTE_ETH_L3_PAYLOAD = 3, - RTE_ETH_L4_PAYLOAD = 4, - RTE_ETH_PAYLOAD_MAX = 8, -} -/** A structure used to select bytes extracted from the protocol layers to - flexible payload for filter*/ -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_flex_payload_cfg { - ///< Payload type - pub type_: rte_eth_payload_type, - pub src_offset: [u16; 16usize], -} -#[test] -fn bindgen_test_layout_rte_eth_flex_payload_cfg() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 36usize, - concat!("Size of: ", stringify!(rte_eth_flex_payload_cfg)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_flex_payload_cfg)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).type_) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_flex_payload_cfg), - "::", - stringify!(type_), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).src_offset) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_flex_payload_cfg), - "::", - stringify!(src_offset), - ), - ); -} -impl Clone for rte_eth_flex_payload_cfg { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_flex_payload_cfg { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -/** A structure used to define FDIR masks for flexible payload - for each flow type*/ -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_fdir_flex_mask { - pub flow_type: u16, - pub mask: [u8; 16usize], -} -#[test] -fn bindgen_test_layout_rte_eth_fdir_flex_mask() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 18usize, - concat!("Size of: ", stringify!(rte_eth_fdir_flex_mask)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_eth_fdir_flex_mask)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).flow_type) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_mask), - "::", - stringify!(flow_type), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mask) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_mask), - "::", - stringify!(mask), - ), - ); -} -impl Clone for rte_eth_fdir_flex_mask { - fn clone(&self) -> Self { - *self - } -} -/** A structure used to define all flexible payload related setting - include flex payload and flex mask*/ -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_fdir_flex_conf { - ///< The number of following payload cfg - pub nb_payloads: u16, - ///< The number of following mask - pub nb_flexmasks: u16, - pub flex_set: [rte_eth_flex_payload_cfg; 8usize], - pub flex_mask: [rte_eth_fdir_flex_mask; 22usize], -} -#[test] -fn bindgen_test_layout_rte_eth_fdir_flex_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 688usize, - concat!("Size of: ", stringify!(rte_eth_fdir_flex_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_fdir_flex_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_payloads) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_conf), - "::", - stringify!(nb_payloads), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_flexmasks) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_conf), - "::", - stringify!(nb_flexmasks), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).flex_set) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_conf), - "::", - stringify!(flex_set), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).flex_mask) as usize - ptr as usize }, - 292usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_fdir_flex_conf), - "::", - stringify!(flex_mask), - ), - ); -} -impl Clone for rte_eth_fdir_flex_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_fdir_flex_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -/** A structure used to configure the Flow Director (FDIR) feature - of an Ethernet port. - - If mode is RTE_FDIR_DISABLE, the pballoc value is ignored.*/ -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct rte_fdir_conf { - ///< Flow Director mode. - pub mode: rte_fdir_mode, - ///< Space for FDIR filters. - pub pballoc: rte_fdir_pballoc_type, - ///< How to report FDIR hash. - pub status: rte_fdir_status_mode, - /// RX queue of packets matching a "drop" filter in perfect mode. - pub drop_queue: u8, - pub mask: rte_eth_fdir_masks, - pub flex_conf: rte_eth_fdir_flex_conf, -} -#[test] -fn bindgen_test_layout_rte_fdir_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 772usize, - concat!("Size of: ", stringify!(rte_fdir_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_fdir_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mode) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_fdir_conf), "::", stringify!(mode)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pballoc) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_fdir_conf), - "::", - stringify!(pballoc), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).status) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(rte_fdir_conf), "::", stringify!(status)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).drop_queue) as usize - ptr as usize }, - 12usize, - concat!( - "Offset of field: ", - stringify!(rte_fdir_conf), - "::", - stringify!(drop_queue), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mask) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(rte_fdir_conf), "::", stringify!(mask)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).flex_conf) as usize - ptr as usize }, - 84usize, - concat!( - "Offset of field: ", - stringify!(rte_fdir_conf), - "::", - stringify!(flex_conf), - ), - ); -} -impl Clone for rte_fdir_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_fdir_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -/// A structure used to enable/disable specific device interrupts. -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_intr_conf { - /// enable/disable lsc interrupt. 0 (default) - disable, 1 enable - pub lsc: u16, - /// enable/disable rxq interrupt. 0 (default) - disable, 1 enable - pub rxq: u16, -} -#[test] -fn bindgen_test_layout_rte_intr_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_intr_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_intr_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).lsc) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_intr_conf), "::", stringify!(lsc)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rxq) as usize - ptr as usize }, - 2usize, - concat!("Offset of field: ", stringify!(rte_intr_conf), "::", stringify!(rxq)), - ); -} -impl Clone for rte_intr_conf { - fn clone(&self) -> Self { - *self - } -} -/** A structure used to configure an Ethernet port. - Depending upon the RX multi-queue mode, extra advanced - configuration settings may be needed.*/ -#[repr(C)] -#[derive(Copy)] -pub struct rte_eth_conf { - /**< bitmap of ETH_LINK_SPEED_XXX of speeds to be -used. ETH_LINK_SPEED_FIXED disables link -autonegotiation, and a unique speed shall be -set. Otherwise, the bitmap defines the set of -speeds to be advertised. If the special value -ETH_LINK_SPEED_AUTONEG (0) is used, all speeds -supported are advertised.*/ - pub link_speeds: u32, - ///< Port RX configuration. - pub rxmode: rte_eth_rxmode, - ///< Port TX configuration. - pub txmode: rte_eth_txmode, - /**< Loopback operation mode. By default the value -is 0, meaning the loopback mode is disabled. -Read the datasheet of given ethernet controller -for details. The possible values of this field -are defined in implementation of each driver.*/ - pub lpbk_mode: u32, - ///< Port RX filtering configuration (union). - pub rx_adv_conf: rte_eth_conf__bindgen_ty_1, - ///< Port TX DCB configuration (union). - pub tx_adv_conf: rte_eth_conf__bindgen_ty_2, - /** Currently,Priority Flow Control(PFC) are supported,if DCB with PFC -is needed,and the variable must be set ETH_DCB_PFC_SUPPORT.*/ - pub dcb_capability_en: u32, - ///< FDIR configuration. - pub fdir_conf: rte_fdir_conf, - ///< Interrupt mode configuration. - pub intr_conf: rte_intr_conf, -} -#[repr(C)] -#[derive(Copy)] -pub struct rte_eth_conf__bindgen_ty_1 { - ///< Port RSS configuration - pub rss_conf: rte_eth_rss_conf, - pub vmdq_dcb_conf: rte_eth_vmdq_dcb_conf, - pub dcb_rx_conf: rte_eth_dcb_rx_conf, - pub vmdq_rx_conf: rte_eth_vmdq_rx_conf, -} -#[test] -fn bindgen_test_layout_rte_eth_conf__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2120usize, - concat!("Size of: ", stringify!(rte_eth_conf__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_eth_conf__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rss_conf) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_1), - "::", - stringify!(rss_conf), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vmdq_dcb_conf) as usize - ptr as usize }, - 24usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_1), - "::", - stringify!(vmdq_dcb_conf), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dcb_rx_conf) as usize - ptr as usize }, - 1064usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_1), - "::", - stringify!(dcb_rx_conf), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vmdq_rx_conf) as usize - ptr as usize }, - 1080usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_1), - "::", - stringify!(vmdq_rx_conf), - ), - ); -} -impl Clone for rte_eth_conf__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_conf__bindgen_ty_1 { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_eth_conf__bindgen_ty_2 { - pub vmdq_dcb_tx_conf: __BindgenUnionField, - pub dcb_tx_conf: __BindgenUnionField, - pub vmdq_tx_conf: __BindgenUnionField, - pub bindgen_union_field: [u32; 3usize], -} -#[test] -fn bindgen_test_layout_rte_eth_conf__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rte_eth_conf__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_eth_conf__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vmdq_dcb_tx_conf) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_2), - "::", - stringify!(vmdq_dcb_tx_conf), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dcb_tx_conf) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_2), - "::", - stringify!(dcb_tx_conf), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vmdq_tx_conf) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf__bindgen_ty_2), - "::", - stringify!(vmdq_tx_conf), - ), - ); -} -impl Clone for rte_eth_conf__bindgen_ty_2 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_eth_conf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2944usize, - concat!("Size of: ", stringify!(rte_eth_conf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_eth_conf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).link_speeds) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(link_speeds), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rxmode) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(rte_eth_conf), "::", stringify!(rxmode)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).txmode) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(rte_eth_conf), "::", stringify!(txmode)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).lpbk_mode) as usize - ptr as usize }, - 24usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(lpbk_mode), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rx_adv_conf) as usize - ptr as usize }, - 32usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(rx_adv_conf), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tx_adv_conf) as usize - ptr as usize }, - 2152usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(tx_adv_conf), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).dcb_capability_en) as usize - ptr as usize - }, - 2164usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(dcb_capability_en), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).fdir_conf) as usize - ptr as usize }, - 2168usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(fdir_conf), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).intr_conf) as usize - ptr as usize }, - 2940usize, - concat!( - "Offset of field: ", - stringify!(rte_eth_conf), - "::", - stringify!(intr_conf), - ), - ); -} -impl Clone for rte_eth_conf { - fn clone(&self) -> Self { - *self - } -} -impl Default for rte_eth_conf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} diff --git a/bindgen-tests/tests/expectations/tests/layout_kni_mbuf.rs b/bindgen-tests/tests/expectations/tests/layout_kni_mbuf.rs index 258ac0d3dc..a9d779e9a1 100644 --- a/bindgen-tests/tests/expectations/tests/layout_kni_mbuf.rs +++ b/bindgen-tests/tests/expectations/tests/layout_kni_mbuf.rs @@ -30,110 +30,81 @@ pub struct rte_kni_mbuf { fn bindgen_test_layout_rte_kni_mbuf() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 128usize, - concat!("Size of: ", stringify!(rte_kni_mbuf)), - ); + assert_eq!(::std::mem::size_of::(), 128usize, "Size of rte_kni_mbuf"); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(rte_kni_mbuf)), + "Alignment of rte_kni_mbuf", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).buf_addr) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_kni_mbuf), - "::", - stringify!(buf_addr), - ), + "Offset of field: rte_kni_mbuf::buf_addr", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).buf_physaddr) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_kni_mbuf), - "::", - stringify!(buf_physaddr), - ), + "Offset of field: rte_kni_mbuf::buf_physaddr", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pad0) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(pad0)), + "Offset of field: rte_kni_mbuf::pad0", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).data_off) as usize - ptr as usize }, 18usize, - concat!( - "Offset of field: ", - stringify!(rte_kni_mbuf), - "::", - stringify!(data_off), - ), + "Offset of field: rte_kni_mbuf::data_off", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pad1) as usize - ptr as usize }, 20usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(pad1)), + "Offset of field: rte_kni_mbuf::pad1", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_segs) as usize - ptr as usize }, 22usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(nb_segs)), + "Offset of field: rte_kni_mbuf::nb_segs", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pad4) as usize - ptr as usize }, 23usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(pad4)), + "Offset of field: rte_kni_mbuf::pad4", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).ol_flags) as usize - ptr as usize }, 24usize, - concat!( - "Offset of field: ", - stringify!(rte_kni_mbuf), - "::", - stringify!(ol_flags), - ), + "Offset of field: rte_kni_mbuf::ol_flags", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pad2) as usize - ptr as usize }, 32usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(pad2)), + "Offset of field: rte_kni_mbuf::pad2", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pkt_len) as usize - ptr as usize }, 36usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(pkt_len)), + "Offset of field: rte_kni_mbuf::pkt_len", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).data_len) as usize - ptr as usize }, 40usize, - concat!( - "Offset of field: ", - stringify!(rte_kni_mbuf), - "::", - stringify!(data_len), - ), + "Offset of field: rte_kni_mbuf::data_len", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pad3) as usize - ptr as usize }, 64usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(pad3)), + "Offset of field: rte_kni_mbuf::pad3", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pool) as usize - ptr as usize }, 72usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(pool)), + "Offset of field: rte_kni_mbuf::pool", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).next) as usize - ptr as usize }, 80usize, - concat!("Offset of field: ", stringify!(rte_kni_mbuf), "::", stringify!(next)), + "Offset of field: rte_kni_mbuf::next", ); } impl Default for rte_kni_mbuf { diff --git a/bindgen-tests/tests/expectations/tests/layout_large_align_field.rs b/bindgen-tests/tests/expectations/tests/layout_large_align_field.rs index 05a9784356..b72c221dca 100644 --- a/bindgen-tests/tests/expectations/tests/layout_large_align_field.rs +++ b/bindgen-tests/tests/expectations/tests/layout_large_align_field.rs @@ -61,30 +61,22 @@ pub struct ip_frag { fn bindgen_test_layout_ip_frag() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(ip_frag)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(ip_frag)), - ); + assert_eq!(::std::mem::size_of::(), 16usize, "Size of ip_frag"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of ip_frag"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).ofs) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(ip_frag), "::", stringify!(ofs)), + "Offset of field: ip_frag::ofs", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).len) as usize - ptr as usize }, 2usize, - concat!("Offset of field: ", stringify!(ip_frag), "::", stringify!(len)), + "Offset of field: ip_frag::len", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mb) as usize - ptr as usize }, 8usize, - concat!("Offset of field: ", stringify!(ip_frag), "::", stringify!(mb)), + "Offset of field: ip_frag::mb", ); } impl Default for ip_frag { @@ -111,30 +103,26 @@ pub struct ip_frag_key { fn bindgen_test_layout_ip_frag_key() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 40usize, - concat!("Size of: ", stringify!(ip_frag_key)), - ); + assert_eq!(::std::mem::size_of::(), 40usize, "Size of ip_frag_key"); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(ip_frag_key)), + "Alignment of ip_frag_key", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).src_dst) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(ip_frag_key), "::", stringify!(src_dst)), + "Offset of field: ip_frag_key::src_dst", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).id) as usize - ptr as usize }, 32usize, - concat!("Offset of field: ", stringify!(ip_frag_key), "::", stringify!(id)), + "Offset of field: ip_frag_key::id", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).key_len) as usize - ptr as usize }, 36usize, - concat!("Offset of field: ", stringify!(ip_frag_key), "::", stringify!(key_len)), + "Offset of field: ip_frag_key::key_len", ); } /** @internal Fragmented packet to reassemble. @@ -171,32 +159,22 @@ fn bindgen_test_layout_ip_frag_pkt__bindgen_ty_1() { assert_eq!( ::std::mem::size_of::(), 16usize, - concat!("Size of: ", stringify!(ip_frag_pkt__bindgen_ty_1)), + "Size of ip_frag_pkt__bindgen_ty_1", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(ip_frag_pkt__bindgen_ty_1)), + "Alignment of ip_frag_pkt__bindgen_ty_1", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tqe_next) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_pkt__bindgen_ty_1), - "::", - stringify!(tqe_next), - ), + "Offset of field: ip_frag_pkt__bindgen_ty_1::tqe_next", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tqe_prev) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_pkt__bindgen_ty_1), - "::", - stringify!(tqe_prev), - ), + "Offset of field: ip_frag_pkt__bindgen_ty_1::tqe_prev", ); } impl Default for ip_frag_pkt__bindgen_ty_1 { @@ -212,60 +190,46 @@ impl Default for ip_frag_pkt__bindgen_ty_1 { fn bindgen_test_layout_ip_frag_pkt() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 192usize, - concat!("Size of: ", stringify!(ip_frag_pkt)), - ); + assert_eq!(::std::mem::size_of::(), 192usize, "Size of ip_frag_pkt"); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(ip_frag_pkt)), + "Alignment of ip_frag_pkt", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).lru) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(lru)), + "Offset of field: ip_frag_pkt::lru", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).key) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(key)), + "Offset of field: ip_frag_pkt::key", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).start) as usize - ptr as usize }, 56usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(start)), + "Offset of field: ip_frag_pkt::start", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).total_size) as usize - ptr as usize }, 64usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_pkt), - "::", - stringify!(total_size), - ), + "Offset of field: ip_frag_pkt::total_size", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).frag_size) as usize - ptr as usize }, 68usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_pkt), - "::", - stringify!(frag_size), - ), + "Offset of field: ip_frag_pkt::frag_size", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).last_idx) as usize - ptr as usize }, 72usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(last_idx)), + "Offset of field: ip_frag_pkt::last_idx", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).frags) as usize - ptr as usize }, 80usize, - concat!("Offset of field: ", stringify!(ip_frag_pkt), "::", stringify!(frags)), + "Offset of field: ip_frag_pkt::frags", ); } impl Default for ip_frag_pkt { @@ -287,30 +251,21 @@ pub struct ip_pkt_list { fn bindgen_test_layout_ip_pkt_list() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(ip_pkt_list)), - ); + assert_eq!(::std::mem::size_of::(), 16usize, "Size of ip_pkt_list"); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(ip_pkt_list)), + "Alignment of ip_pkt_list", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tqh_first) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(ip_pkt_list), - "::", - stringify!(tqh_first), - ), + "Offset of field: ip_pkt_list::tqh_first", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).tqh_last) as usize - ptr as usize }, 8usize, - concat!("Offset of field: ", stringify!(ip_pkt_list), "::", stringify!(tqh_last)), + "Offset of field: ip_pkt_list::tqh_last", ); } impl Default for ip_pkt_list { @@ -347,72 +302,42 @@ fn bindgen_test_layout_ip_frag_tbl_stat() { assert_eq!( ::std::mem::size_of::(), 64usize, - concat!("Size of: ", stringify!(ip_frag_tbl_stat)), + "Size of ip_frag_tbl_stat", ); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(ip_frag_tbl_stat)), + "Alignment of ip_frag_tbl_stat", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).find_num) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_tbl_stat), - "::", - stringify!(find_num), - ), + "Offset of field: ip_frag_tbl_stat::find_num", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).add_num) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_tbl_stat), - "::", - stringify!(add_num), - ), + "Offset of field: ip_frag_tbl_stat::add_num", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).del_num) as usize - ptr as usize }, 16usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_tbl_stat), - "::", - stringify!(del_num), - ), + "Offset of field: ip_frag_tbl_stat::del_num", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).reuse_num) as usize - ptr as usize }, 24usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_tbl_stat), - "::", - stringify!(reuse_num), - ), + "Offset of field: ip_frag_tbl_stat::reuse_num", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).fail_total) as usize - ptr as usize }, 32usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_tbl_stat), - "::", - stringify!(fail_total), - ), + "Offset of field: ip_frag_tbl_stat::fail_total", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).fail_nospace) as usize - ptr as usize }, 40usize, - concat!( - "Offset of field: ", - stringify!(ip_frag_tbl_stat), - "::", - stringify!(fail_nospace), - ), + "Offset of field: ip_frag_tbl_stat::fail_nospace", ); } impl Default for ip_frag_tbl_stat { @@ -459,102 +384,67 @@ fn bindgen_test_layout_rte_ip_frag_tbl() { assert_eq!( ::std::mem::size_of::(), 128usize, - concat!("Size of: ", stringify!(rte_ip_frag_tbl)), + "Size of rte_ip_frag_tbl", ); assert_eq!( ::std::mem::align_of::(), 64usize, - concat!("Alignment of ", stringify!(rte_ip_frag_tbl)), + "Alignment of rte_ip_frag_tbl", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).max_cycles) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(rte_ip_frag_tbl), - "::", - stringify!(max_cycles), - ), + "Offset of field: rte_ip_frag_tbl::max_cycles", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).entry_mask) as usize - ptr as usize }, 8usize, - concat!( - "Offset of field: ", - stringify!(rte_ip_frag_tbl), - "::", - stringify!(entry_mask), - ), + "Offset of field: rte_ip_frag_tbl::entry_mask", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).max_entries) as usize - ptr as usize }, 12usize, - concat!( - "Offset of field: ", - stringify!(rte_ip_frag_tbl), - "::", - stringify!(max_entries), - ), + "Offset of field: rte_ip_frag_tbl::max_entries", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).use_entries) as usize - ptr as usize }, 16usize, - concat!( - "Offset of field: ", - stringify!(rte_ip_frag_tbl), - "::", - stringify!(use_entries), - ), + "Offset of field: rte_ip_frag_tbl::use_entries", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).bucket_entries) as usize - ptr as usize }, 20usize, - concat!( - "Offset of field: ", - stringify!(rte_ip_frag_tbl), - "::", - stringify!(bucket_entries), - ), + "Offset of field: rte_ip_frag_tbl::bucket_entries", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_entries) as usize - ptr as usize }, 24usize, - concat!( - "Offset of field: ", - stringify!(rte_ip_frag_tbl), - "::", - stringify!(nb_entries), - ), + "Offset of field: rte_ip_frag_tbl::nb_entries", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).nb_buckets) as usize - ptr as usize }, 28usize, - concat!( - "Offset of field: ", - stringify!(rte_ip_frag_tbl), - "::", - stringify!(nb_buckets), - ), + "Offset of field: rte_ip_frag_tbl::nb_buckets", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).last) as usize - ptr as usize }, 32usize, - concat!("Offset of field: ", stringify!(rte_ip_frag_tbl), "::", stringify!(last)), + "Offset of field: rte_ip_frag_tbl::last", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).lru) as usize - ptr as usize }, 40usize, - concat!("Offset of field: ", stringify!(rte_ip_frag_tbl), "::", stringify!(lru)), + "Offset of field: rte_ip_frag_tbl::lru", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).stat) as usize - ptr as usize }, 64usize, - concat!("Offset of field: ", stringify!(rte_ip_frag_tbl), "::", stringify!(stat)), + "Offset of field: rte_ip_frag_tbl::stat", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).pkt) as usize - ptr as usize }, 128usize, - concat!("Offset of field: ", stringify!(rte_ip_frag_tbl), "::", stringify!(pkt)), + "Offset of field: rte_ip_frag_tbl::pkt", ); } impl Default for rte_ip_frag_tbl { diff --git a/bindgen-tests/tests/expectations/tests/layout_mbuf.rs b/bindgen-tests/tests/expectations/tests/layout_mbuf.rs index a04f0274d1..cb3698812b 100644 --- a/bindgen-tests/tests/expectations/tests/layout_mbuf.rs +++ b/bindgen-tests/tests/expectations/tests/layout_mbuf.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } pub const RTE_CACHE_LINE_MIN_SIZE: u32 = 64; pub const RTE_CACHE_LINE_SIZE: u32 = 64; @@ -96,26 +158,14 @@ pub struct rte_atomic16_t { ///< An internal counter value. pub cnt: i16, } -#[test] -fn bindgen_test_layout_rte_atomic16_t() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(rte_atomic16_t)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_atomic16_t)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cnt) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_atomic16_t), "::", stringify!(cnt)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_atomic16_t"][::std::mem::size_of::() - 2usize]; + ["Alignment of rte_atomic16_t"][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: rte_atomic16_t::cnt", + ][::std::mem::offset_of!(rte_atomic16_t, cnt) - 0usize]; +}; /// The generic rte_mbuf, containing a packet mbuf. #[repr(C)] #[repr(align(64))] @@ -177,41 +227,21 @@ pub union rte_mbuf__bindgen_ty_1 { ///< Non-atomically accessed refcnt pub refcnt: u16, } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).refcnt_atomic) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_1), - "::", - stringify!(refcnt_atomic), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).refcnt) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_1), - "::", - stringify!(refcnt), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_1", + ][::std::mem::size_of::() - 2usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_1", + ][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_1::refcnt_atomic", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_1, refcnt_atomic) - 0usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_1::refcnt", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_1, refcnt) - 0usize]; +}; impl Default for rte_mbuf__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -235,19 +265,15 @@ pub struct rte_mbuf__bindgen_ty_2__bindgen_ty_1 { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_2__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_2__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_2__bindgen_ty_1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_2__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_2__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; +}; impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { #[inline] pub fn l2_type(&self) -> u32 { @@ -261,6 +287,31 @@ impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { } } #[inline] + pub unsafe fn l2_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_l2_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn l3_type(&self) -> u32 { unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u32) } } @@ -272,6 +323,31 @@ impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { } } #[inline] + pub unsafe fn l3_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 4usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_l3_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn l4_type(&self) -> u32 { unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 4u8) as u32) } } @@ -283,6 +359,31 @@ impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { } } #[inline] + pub unsafe fn l4_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 8usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_l4_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn tun_type(&self) -> u32 { unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 4u8) as u32) } } @@ -294,6 +395,31 @@ impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { } } #[inline] + pub unsafe fn tun_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 12usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_tun_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn inner_l2_type(&self) -> u32 { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 4u8) as u32) } } @@ -305,6 +431,31 @@ impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { } } #[inline] + pub unsafe fn inner_l2_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_inner_l2_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn inner_l3_type(&self) -> u32 { unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 4u8) as u32) } } @@ -316,6 +467,31 @@ impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { } } #[inline] + pub unsafe fn inner_l3_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 20usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_inner_l3_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn inner_l4_type(&self) -> u32 { unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 4u8) as u32) } } @@ -327,6 +503,31 @@ impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { } } #[inline] + pub unsafe fn inner_l4_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 24usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_inner_l4_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( l2_type: u32, l3_type: u32, @@ -409,31 +610,18 @@ impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { __bindgen_bitfield_unit } } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).packet_type) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_2), - "::", - stringify!(packet_type), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_2", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_2", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_2::packet_type", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_2, packet_type) - 0usize]; +}; impl Default for rte_mbuf__bindgen_ty_2 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -473,86 +661,44 @@ pub struct rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 { pub hash: u16, pub id: u16, } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit< +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::< rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, - > = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::< - rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, - >(), - 4usize, - concat!( - "Size of: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1), - ), - ); - assert_eq!( - ::std::mem::align_of::< - rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, - >(), - 2usize, - concat!( - "Alignment of ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hash) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(hash), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).id) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(id), - ), - ); -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit< - rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1, - > = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!( - "Size of: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1), - ), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!( - "Alignment of ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).lo) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(lo), - ), - ); -} + >() - 4usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::< + rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, + >() - 2usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1::hash", + ][::std::mem::offset_of!( + rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, hash + ) - 0usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1::id", + ][::std::mem::offset_of!( + rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, id + ) - 2usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::() + - 4usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::() + - 4usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1::lo", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1, lo) + - 0usize]; +}; impl Default for rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -562,31 +708,18 @@ impl Default for rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hi) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1), - "::", - stringify!(hi), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_3__bindgen_ty_1", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_3__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3__bindgen_ty_1::hi", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_3__bindgen_ty_1, hi) - 4usize]; +}; impl Default for rte_mbuf__bindgen_ty_3__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -602,96 +735,42 @@ pub struct rte_mbuf__bindgen_ty_3__bindgen_ty_2 { pub lo: u32, pub hi: u32, } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).lo) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_2), - "::", - stringify!(lo), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hi) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_2), - "::", - stringify!(hi), - ), - ); -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_3)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_3)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rss) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3), - "::", - stringify!(rss), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).fdir) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3), - "::", - stringify!(fdir), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sched) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3), - "::", - stringify!(sched), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).usr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3), - "::", - stringify!(usr), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_3__bindgen_ty_2", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_3__bindgen_ty_2", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3__bindgen_ty_2::lo", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_3__bindgen_ty_2, lo) - 0usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3__bindgen_ty_2::hi", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_3__bindgen_ty_2, hi) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_3", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_3", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3::rss", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_3, rss) - 0usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3::fdir", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_3, fdir) - 0usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3::sched", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_3, sched) - 0usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_3::usr", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_3, usr) - 0usize]; +}; impl Default for rte_mbuf__bindgen_ty_3 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -709,41 +788,21 @@ pub union rte_mbuf__bindgen_ty_4 { ///< Allow 8-byte userdata on 32-bit pub udata64: u64, } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_4() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_4)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_4)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).userdata) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_4), - "::", - stringify!(userdata), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).udata64) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_4), - "::", - stringify!(udata64), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_4", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_4", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_4::userdata", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_4, userdata) - 0usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_4::udata64", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_4, udata64) - 0usize]; +}; impl Default for rte_mbuf__bindgen_ty_4 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -767,19 +826,15 @@ pub struct rte_mbuf__bindgen_ty_5__bindgen_ty_1 { pub _bitfield_align_1: [u16; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 7usize]>, } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_5__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_5__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_5__bindgen_ty_1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_5__bindgen_ty_1", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_5__bindgen_ty_1", + ][::std::mem::align_of::() - 8usize]; +}; impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { #[inline] pub fn l2_len(&self) -> u64 { @@ -793,6 +848,31 @@ impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { } } #[inline] + pub unsafe fn l2_len_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 7u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_l2_len_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 7u8, + val as u64, + ) + } + } + #[inline] pub fn l3_len(&self) -> u64 { unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 9u8) as u64) } } @@ -804,6 +884,31 @@ impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { } } #[inline] + pub unsafe fn l3_len_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 7usize, 9u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_l3_len_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 9u8, + val as u64, + ) + } + } + #[inline] pub fn l4_len(&self) -> u64 { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 8u8) as u64) } } @@ -815,6 +920,31 @@ impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { } } #[inline] + pub unsafe fn l4_len_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 8u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_l4_len_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 8u8, + val as u64, + ) + } + } + #[inline] pub fn tso_segsz(&self) -> u64 { unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 16u8) as u64) } } @@ -826,6 +956,31 @@ impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { } } #[inline] + pub unsafe fn tso_segsz_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 24usize, 16u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_tso_segsz_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 16u8, + val as u64, + ) + } + } + #[inline] pub fn outer_l3_len(&self) -> u64 { unsafe { ::std::mem::transmute(self._bitfield_1.get(40usize, 9u8) as u64) } } @@ -837,6 +992,31 @@ impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { } } #[inline] + pub unsafe fn outer_l3_len_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 40usize, 9u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_outer_l3_len_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 40usize, + 9u8, + val as u64, + ) + } + } + #[inline] pub fn outer_l2_len(&self) -> u64 { unsafe { ::std::mem::transmute(self._bitfield_1.get(49usize, 7u8) as u64) } } @@ -848,6 +1028,31 @@ impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { } } #[inline] + pub unsafe fn outer_l2_len_raw(this: *const Self) -> u64 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 49usize, 7u8) + as u64, + ) + } + } + #[inline] + pub unsafe fn set_outer_l2_len_raw(this: *mut Self, val: u64) { + unsafe { + let val: u64 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 7usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 49usize, + 7u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( l2_len: u64, l3_len: u64, @@ -918,31 +1123,18 @@ impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { __bindgen_bitfield_unit } } -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_5() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_5)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_5)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tx_offload) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_5), - "::", - stringify!(tx_offload), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of rte_mbuf__bindgen_ty_5", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of rte_mbuf__bindgen_ty_5", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: rte_mbuf__bindgen_ty_5::tx_offload", + ][::std::mem::offset_of!(rte_mbuf__bindgen_ty_5, tx_offload) - 0usize]; +}; impl Default for rte_mbuf__bindgen_ty_5 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -952,143 +1144,74 @@ impl Default for rte_mbuf__bindgen_ty_5 { } } } -#[test] -fn bindgen_test_layout_rte_mbuf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 128usize, - concat!("Size of: ", stringify!(rte_mbuf)), - ); - assert_eq!( - ::std::mem::align_of::(), - 64usize, - concat!("Alignment of ", stringify!(rte_mbuf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cacheline0) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(cacheline0)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).buf_addr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(buf_addr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).buf_physaddr) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf), - "::", - stringify!(buf_physaddr), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).buf_len) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(buf_len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rearm_data) as usize - ptr as usize }, - 18usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(rearm_data)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).data_off) as usize - ptr as usize }, - 18usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(data_off)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_segs) as usize - ptr as usize }, - 22usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(nb_segs)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).port) as usize - ptr as usize }, - 23usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(port)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ol_flags) as usize - ptr as usize }, - 24usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(ol_flags)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).rx_descriptor_fields1) as usize - ptr as usize - }, - 32usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf), - "::", - stringify!(rx_descriptor_fields1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pkt_len) as usize - ptr as usize }, - 36usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(pkt_len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).data_len) as usize - ptr as usize }, - 40usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(data_len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vlan_tci) as usize - ptr as usize }, - 42usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(vlan_tci)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hash) as usize - ptr as usize }, - 44usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(hash)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).seqn) as usize - ptr as usize }, - 52usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(seqn)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vlan_tci_outer) as usize - ptr as usize }, - 56usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf), - "::", - stringify!(vlan_tci_outer), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cacheline1) as usize - ptr as usize }, - 64usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(cacheline1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pool) as usize - ptr as usize }, - 72usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(pool)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).next) as usize - ptr as usize }, - 80usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(next)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).priv_size) as usize - ptr as usize }, - 96usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(priv_size)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).timesync) as usize - ptr as usize }, - 98usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(timesync)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of rte_mbuf"][::std::mem::size_of::() - 128usize]; + ["Alignment of rte_mbuf"][::std::mem::align_of::() - 64usize]; + [ + "Offset of field: rte_mbuf::cacheline0", + ][::std::mem::offset_of!(rte_mbuf, cacheline0) - 0usize]; + [ + "Offset of field: rte_mbuf::buf_addr", + ][::std::mem::offset_of!(rte_mbuf, buf_addr) - 0usize]; + [ + "Offset of field: rte_mbuf::buf_physaddr", + ][::std::mem::offset_of!(rte_mbuf, buf_physaddr) - 8usize]; + [ + "Offset of field: rte_mbuf::buf_len", + ][::std::mem::offset_of!(rte_mbuf, buf_len) - 16usize]; + [ + "Offset of field: rte_mbuf::rearm_data", + ][::std::mem::offset_of!(rte_mbuf, rearm_data) - 18usize]; + [ + "Offset of field: rte_mbuf::data_off", + ][::std::mem::offset_of!(rte_mbuf, data_off) - 18usize]; + [ + "Offset of field: rte_mbuf::nb_segs", + ][::std::mem::offset_of!(rte_mbuf, nb_segs) - 22usize]; + [ + "Offset of field: rte_mbuf::port", + ][::std::mem::offset_of!(rte_mbuf, port) - 23usize]; + [ + "Offset of field: rte_mbuf::ol_flags", + ][::std::mem::offset_of!(rte_mbuf, ol_flags) - 24usize]; + [ + "Offset of field: rte_mbuf::rx_descriptor_fields1", + ][::std::mem::offset_of!(rte_mbuf, rx_descriptor_fields1) - 32usize]; + [ + "Offset of field: rte_mbuf::pkt_len", + ][::std::mem::offset_of!(rte_mbuf, pkt_len) - 36usize]; + [ + "Offset of field: rte_mbuf::data_len", + ][::std::mem::offset_of!(rte_mbuf, data_len) - 40usize]; + [ + "Offset of field: rte_mbuf::vlan_tci", + ][::std::mem::offset_of!(rte_mbuf, vlan_tci) - 42usize]; + [ + "Offset of field: rte_mbuf::hash", + ][::std::mem::offset_of!(rte_mbuf, hash) - 44usize]; + [ + "Offset of field: rte_mbuf::seqn", + ][::std::mem::offset_of!(rte_mbuf, seqn) - 52usize]; + [ + "Offset of field: rte_mbuf::vlan_tci_outer", + ][::std::mem::offset_of!(rte_mbuf, vlan_tci_outer) - 56usize]; + [ + "Offset of field: rte_mbuf::cacheline1", + ][::std::mem::offset_of!(rte_mbuf, cacheline1) - 64usize]; + [ + "Offset of field: rte_mbuf::pool", + ][::std::mem::offset_of!(rte_mbuf, pool) - 72usize]; + [ + "Offset of field: rte_mbuf::next", + ][::std::mem::offset_of!(rte_mbuf, next) - 80usize]; + [ + "Offset of field: rte_mbuf::priv_size", + ][::std::mem::offset_of!(rte_mbuf, priv_size) - 96usize]; + [ + "Offset of field: rte_mbuf::timesync", + ][::std::mem::offset_of!(rte_mbuf, timesync) - 98usize]; +}; impl Default for rte_mbuf { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/layout_mbuf_1_0.rs b/bindgen-tests/tests/expectations/tests/layout_mbuf_1_0.rs deleted file mode 100644 index 129300790b..0000000000 --- a/bindgen-tests/tests/expectations/tests/layout_mbuf_1_0.rs +++ /dev/null @@ -1,1154 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub struct __BindgenBitfieldUnit { - storage: Storage, -} -impl __BindgenBitfieldUnit { - #[inline] - pub fn new(storage: Storage) -> Self { - Self { storage } - } -} -impl __BindgenBitfieldUnit -where - Storage: AsRef<[u8]> + AsMut<[u8]>, -{ - #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - byte & mask == mask - } - #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } - } - #[inline] - pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - let mut val = 0; - for i in 0..(bit_width as usize) { - if self.get_bit(i + bit_offset) { - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - val |= 1 << index; - } - } - val - } - #[inline] - pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - for i in 0..(bit_width as usize) { - let mask = 1 << i; - let val_bit_is_set = val & mask == mask; - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - self.set_bit(index + bit_offset, val_bit_is_set); - } - } -} -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -pub const RTE_CACHE_LINE_MIN_SIZE: u32 = 64; -pub const RTE_CACHE_LINE_SIZE: u32 = 64; -pub type phys_addr_t = u64; -pub type MARKER = [*mut ::std::os::raw::c_void; 0usize]; -pub type MARKER8 = [u8; 0usize]; -pub type MARKER64 = [u64; 0usize]; -/// The atomic counter structure. -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_atomic16_t { - ///< An internal counter value. - pub cnt: i16, -} -#[test] -fn bindgen_test_layout_rte_atomic16_t() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(rte_atomic16_t)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_atomic16_t)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cnt) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_atomic16_t), "::", stringify!(cnt)), - ); -} -impl Clone for rte_atomic16_t { - fn clone(&self) -> Self { - *self - } -} -/// The generic rte_mbuf, containing a packet mbuf. -#[repr(C)] -pub struct rte_mbuf { - pub cacheline0: MARKER, - ///< Virtual address of segment buffer. - pub buf_addr: *mut ::std::os::raw::c_void, - ///< Physical address of segment buffer. - pub buf_physaddr: phys_addr_t, - ///< Length of segment buffer. - pub buf_len: u16, - pub rearm_data: MARKER8, - pub data_off: u16, - pub __bindgen_anon_1: rte_mbuf__bindgen_ty_1, - ///< Number of segments. - pub nb_segs: u8, - ///< Input port. - pub port: u8, - ///< Offload features. - pub ol_flags: u64, - pub rx_descriptor_fields1: MARKER, - pub __bindgen_anon_2: rte_mbuf__bindgen_ty_2, - ///< Total pkt len: sum of all segments. - pub pkt_len: u32, - ///< Amount of data in segment buffer. - pub data_len: u16, - /// VLAN TCI (CPU order), valid if PKT_RX_VLAN_STRIPPED is set. - pub vlan_tci: u16, - ///< hash information - pub hash: rte_mbuf__bindgen_ty_3, - ///< Sequence number. See also rte_reorder_insert() - pub seqn: u32, - /// Outer VLAN TCI (CPU order), valid if PKT_RX_QINQ_STRIPPED is set. - pub vlan_tci_outer: u16, - pub cacheline1: MARKER, - pub __bindgen_anon_3: rte_mbuf__bindgen_ty_4, - ///< Pool from which mbuf was allocated. - pub pool: *mut rte_mempool, - ///< Next segment of scattered packet. - pub next: *mut rte_mbuf, - pub __bindgen_anon_4: rte_mbuf__bindgen_ty_5, - /** Size of the application private data. In case of an indirect - mbuf, it stores the direct mbuf private data size.*/ - pub priv_size: u16, - /// Timesync flags for use with IEEE1588. - pub timesync: u16, - pub __bindgen_padding_0: [u32; 7usize], -} -/** 16-bit Reference counter. - It should only be accessed using the following functions: - rte_mbuf_refcnt_update(), rte_mbuf_refcnt_read(), and - rte_mbuf_refcnt_set(). The functionality of these functions (atomic, - or non-atomic) is controlled by the CONFIG_RTE_MBUF_REFCNT_ATOMIC - config option.*/ -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_1 { - ///< Atomically accessed refcnt - pub refcnt_atomic: __BindgenUnionField, - ///< Non-atomically accessed refcnt - pub refcnt: __BindgenUnionField, - pub bindgen_union_field: u16, -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).refcnt_atomic) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_1), - "::", - stringify!(refcnt_atomic), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).refcnt) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_1), - "::", - stringify!(refcnt), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_2 { - ///< L2/L3/L4 and tunnel information. - pub packet_type: __BindgenUnionField, - pub __bindgen_anon_1: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_2__bindgen_ty_1 { - pub _bitfield_align_1: [u8; 0], - pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, - pub __bindgen_align: [u32; 0usize], -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_2__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_2__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_2__bindgen_ty_1)), - ); -} -impl Clone for rte_mbuf__bindgen_ty_2__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -impl rte_mbuf__bindgen_ty_2__bindgen_ty_1 { - #[inline] - pub fn l2_type(&self) -> u32 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 4u8) as u32) } - } - #[inline] - pub fn set_l2_type(&mut self, val: u32) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(0usize, 4u8, val as u64) - } - } - #[inline] - pub fn l3_type(&self) -> u32 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u32) } - } - #[inline] - pub fn set_l3_type(&mut self, val: u32) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(4usize, 4u8, val as u64) - } - } - #[inline] - pub fn l4_type(&self) -> u32 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 4u8) as u32) } - } - #[inline] - pub fn set_l4_type(&mut self, val: u32) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(8usize, 4u8, val as u64) - } - } - #[inline] - pub fn tun_type(&self) -> u32 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 4u8) as u32) } - } - #[inline] - pub fn set_tun_type(&mut self, val: u32) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(12usize, 4u8, val as u64) - } - } - #[inline] - pub fn inner_l2_type(&self) -> u32 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 4u8) as u32) } - } - #[inline] - pub fn set_inner_l2_type(&mut self, val: u32) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(16usize, 4u8, val as u64) - } - } - #[inline] - pub fn inner_l3_type(&self) -> u32 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 4u8) as u32) } - } - #[inline] - pub fn set_inner_l3_type(&mut self, val: u32) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(20usize, 4u8, val as u64) - } - } - #[inline] - pub fn inner_l4_type(&self) -> u32 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 4u8) as u32) } - } - #[inline] - pub fn set_inner_l4_type(&mut self, val: u32) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(24usize, 4u8, val as u64) - } - } - #[inline] - pub fn new_bitfield_1( - l2_type: u32, - l3_type: u32, - l4_type: u32, - tun_type: u32, - inner_l2_type: u32, - inner_l3_type: u32, - inner_l4_type: u32, - ) -> __BindgenBitfieldUnit<[u8; 4usize]> { - let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); - __bindgen_bitfield_unit - .set( - 0usize, - 4u8, - { - let l2_type: u32 = unsafe { ::std::mem::transmute(l2_type) }; - l2_type as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 4usize, - 4u8, - { - let l3_type: u32 = unsafe { ::std::mem::transmute(l3_type) }; - l3_type as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 8usize, - 4u8, - { - let l4_type: u32 = unsafe { ::std::mem::transmute(l4_type) }; - l4_type as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 12usize, - 4u8, - { - let tun_type: u32 = unsafe { ::std::mem::transmute(tun_type) }; - tun_type as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 16usize, - 4u8, - { - let inner_l2_type: u32 = unsafe { - ::std::mem::transmute(inner_l2_type) - }; - inner_l2_type as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 20usize, - 4u8, - { - let inner_l3_type: u32 = unsafe { - ::std::mem::transmute(inner_l3_type) - }; - inner_l3_type as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 24usize, - 4u8, - { - let inner_l4_type: u32 = unsafe { - ::std::mem::transmute(inner_l4_type) - }; - inner_l4_type as u64 - }, - ); - __bindgen_bitfield_unit - } -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).packet_type) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_2), - "::", - stringify!(packet_type), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_2 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_3 { - ///< RSS hash result if RSS enabled - pub rss: __BindgenUnionField, - ///< Filter identifier if FDIR enabled - pub fdir: __BindgenUnionField, - ///< Hierarchical scheduler - pub sched: __BindgenUnionField, - ///< User defined tags. See rte_distributor_process() - pub usr: __BindgenUnionField, - pub bindgen_union_field: [u32; 2usize], -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_3__bindgen_ty_1 { - pub __bindgen_anon_1: rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1, - pub hi: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1 { - pub __bindgen_anon_1: __BindgenUnionField< - rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, - >, - pub lo: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 { - pub hash: u16, - pub id: u16, -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit< - rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, - > = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::< - rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, - >(), - 4usize, - concat!( - "Size of: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1), - ), - ); - assert_eq!( - ::std::mem::align_of::< - rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, - >(), - 2usize, - concat!( - "Alignment of ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hash) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(hash), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).id) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(id), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit< - rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1, - > = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!( - "Size of: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1), - ), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!( - "Alignment of ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).lo) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(lo), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_3__bindgen_ty_1__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hi) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_1), - "::", - stringify!(hi), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_3__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_3__bindgen_ty_2 { - pub lo: u32, - pub hi: u32, -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).lo) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_2), - "::", - stringify!(lo), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hi) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3__bindgen_ty_2), - "::", - stringify!(hi), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_3__bindgen_ty_2 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_3() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_3)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_3)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rss) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3), - "::", - stringify!(rss), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).fdir) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3), - "::", - stringify!(fdir), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).sched) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3), - "::", - stringify!(sched), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).usr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_3), - "::", - stringify!(usr), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_3 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_4 { - ///< Can be used for external metadata - pub userdata: __BindgenUnionField<*mut ::std::os::raw::c_void>, - ///< Allow 8-byte userdata on 32-bit - pub udata64: __BindgenUnionField, - pub bindgen_union_field: u64, -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_4() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_4)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_4)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).userdata) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_4), - "::", - stringify!(userdata), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).udata64) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_4), - "::", - stringify!(udata64), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_4 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_5 { - ///< combined for easy fetch - pub tx_offload: __BindgenUnionField, - pub __bindgen_anon_1: __BindgenUnionField, - pub bindgen_union_field: u64, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mbuf__bindgen_ty_5__bindgen_ty_1 { - pub _bitfield_align_1: [u16; 0], - pub _bitfield_1: __BindgenBitfieldUnit<[u8; 7usize]>, - pub __bindgen_align: [u64; 0usize], -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_5__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_5__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_5__bindgen_ty_1)), - ); -} -impl Clone for rte_mbuf__bindgen_ty_5__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -impl rte_mbuf__bindgen_ty_5__bindgen_ty_1 { - #[inline] - pub fn l2_len(&self) -> u64 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 7u8) as u64) } - } - #[inline] - pub fn set_l2_len(&mut self, val: u64) { - unsafe { - let val: u64 = ::std::mem::transmute(val); - self._bitfield_1.set(0usize, 7u8, val as u64) - } - } - #[inline] - pub fn l3_len(&self) -> u64 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 9u8) as u64) } - } - #[inline] - pub fn set_l3_len(&mut self, val: u64) { - unsafe { - let val: u64 = ::std::mem::transmute(val); - self._bitfield_1.set(7usize, 9u8, val as u64) - } - } - #[inline] - pub fn l4_len(&self) -> u64 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 8u8) as u64) } - } - #[inline] - pub fn set_l4_len(&mut self, val: u64) { - unsafe { - let val: u64 = ::std::mem::transmute(val); - self._bitfield_1.set(16usize, 8u8, val as u64) - } - } - #[inline] - pub fn tso_segsz(&self) -> u64 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 16u8) as u64) } - } - #[inline] - pub fn set_tso_segsz(&mut self, val: u64) { - unsafe { - let val: u64 = ::std::mem::transmute(val); - self._bitfield_1.set(24usize, 16u8, val as u64) - } - } - #[inline] - pub fn outer_l3_len(&self) -> u64 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(40usize, 9u8) as u64) } - } - #[inline] - pub fn set_outer_l3_len(&mut self, val: u64) { - unsafe { - let val: u64 = ::std::mem::transmute(val); - self._bitfield_1.set(40usize, 9u8, val as u64) - } - } - #[inline] - pub fn outer_l2_len(&self) -> u64 { - unsafe { ::std::mem::transmute(self._bitfield_1.get(49usize, 7u8) as u64) } - } - #[inline] - pub fn set_outer_l2_len(&mut self, val: u64) { - unsafe { - let val: u64 = ::std::mem::transmute(val); - self._bitfield_1.set(49usize, 7u8, val as u64) - } - } - #[inline] - pub fn new_bitfield_1( - l2_len: u64, - l3_len: u64, - l4_len: u64, - tso_segsz: u64, - outer_l3_len: u64, - outer_l2_len: u64, - ) -> __BindgenBitfieldUnit<[u8; 7usize]> { - let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 7usize]> = Default::default(); - __bindgen_bitfield_unit - .set( - 0usize, - 7u8, - { - let l2_len: u64 = unsafe { ::std::mem::transmute(l2_len) }; - l2_len as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 7usize, - 9u8, - { - let l3_len: u64 = unsafe { ::std::mem::transmute(l3_len) }; - l3_len as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 16usize, - 8u8, - { - let l4_len: u64 = unsafe { ::std::mem::transmute(l4_len) }; - l4_len as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 24usize, - 16u8, - { - let tso_segsz: u64 = unsafe { ::std::mem::transmute(tso_segsz) }; - tso_segsz as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 40usize, - 9u8, - { - let outer_l3_len: u64 = unsafe { - ::std::mem::transmute(outer_l3_len) - }; - outer_l3_len as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 49usize, - 7u8, - { - let outer_l2_len: u64 = unsafe { - ::std::mem::transmute(outer_l2_len) - }; - outer_l2_len as u64 - }, - ); - __bindgen_bitfield_unit - } -} -#[test] -fn bindgen_test_layout_rte_mbuf__bindgen_ty_5() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(rte_mbuf__bindgen_ty_5)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rte_mbuf__bindgen_ty_5)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tx_offload) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf__bindgen_ty_5), - "::", - stringify!(tx_offload), - ), - ); -} -impl Clone for rte_mbuf__bindgen_ty_5 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_rte_mbuf() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 128usize, - concat!("Size of: ", stringify!(rte_mbuf)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cacheline0) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(cacheline0)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).buf_addr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(buf_addr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).buf_physaddr) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf), - "::", - stringify!(buf_physaddr), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).buf_len) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(buf_len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rearm_data) as usize - ptr as usize }, - 18usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(rearm_data)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).data_off) as usize - ptr as usize }, - 18usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(data_off)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).nb_segs) as usize - ptr as usize }, - 22usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(nb_segs)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).port) as usize - ptr as usize }, - 23usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(port)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ol_flags) as usize - ptr as usize }, - 24usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(ol_flags)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).rx_descriptor_fields1) as usize - ptr as usize - }, - 32usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf), - "::", - stringify!(rx_descriptor_fields1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pkt_len) as usize - ptr as usize }, - 36usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(pkt_len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).data_len) as usize - ptr as usize }, - 40usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(data_len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vlan_tci) as usize - ptr as usize }, - 42usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(vlan_tci)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).hash) as usize - ptr as usize }, - 44usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(hash)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).seqn) as usize - ptr as usize }, - 52usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(seqn)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).vlan_tci_outer) as usize - ptr as usize }, - 56usize, - concat!( - "Offset of field: ", - stringify!(rte_mbuf), - "::", - stringify!(vlan_tci_outer), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cacheline1) as usize - ptr as usize }, - 64usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(cacheline1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).pool) as usize - ptr as usize }, - 72usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(pool)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).next) as usize - ptr as usize }, - 80usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(next)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).priv_size) as usize - ptr as usize }, - 96usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(priv_size)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).timesync) as usize - ptr as usize }, - 98usize, - concat!("Offset of field: ", stringify!(rte_mbuf), "::", stringify!(timesync)), - ); -} -impl Default for rte_mbuf { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -///< Pool from which mbuf was allocated. -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct rte_mempool { - pub _address: u8, -} -impl Clone for rte_mempool { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/libclang-9/atomic-constant.rs b/bindgen-tests/tests/expectations/tests/libclang-9/atomic-constant.rs new file mode 100644 index 0000000000..098beb43de --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/libclang-9/atomic-constant.rs @@ -0,0 +1,4 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +unsafe extern "C" { + pub static mut b: ::std::os::raw::c_int; +} diff --git a/bindgen-tests/tests/expectations/tests/libclang-9/constified-enum-module-overflow.rs b/bindgen-tests/tests/expectations/tests/libclang-9/constified-enum-module-overflow.rs index 49498deaa5..4f8296c65c 100644 --- a/bindgen-tests/tests/expectations/tests/libclang-9/constified-enum-module-overflow.rs +++ b/bindgen-tests/tests/expectations/tests/libclang-9/constified-enum-module-overflow.rs @@ -15,32 +15,18 @@ pub type C_U = B; pub struct A { pub u: u8, } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(u)), - ); -} -#[test] -fn __bindgen_test_layout_C_open0_A_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(C)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(C)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 1usize]; + ["Alignment of A"][::std::mem::align_of::() - 1usize]; + ["Offset of field: A::u"][::std::mem::offset_of!(A, u) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: C_open0_A_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: C_open0_A_close0", + ][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/libclang-9/issue-544-stylo-creduce-2.rs b/bindgen-tests/tests/expectations/tests/libclang-9/issue-544-stylo-creduce-2.rs index 5c5ad156e3..7f0471bd96 100644 --- a/bindgen-tests/tests/expectations/tests/libclang-9/issue-544-stylo-creduce-2.rs +++ b/bindgen-tests/tests/expectations/tests/libclang-9/issue-544-stylo-creduce-2.rs @@ -1,11 +1,21 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +/// If Bindgen could only determine the size and alignment of a +/// type, it is represented like this. +#[derive(PartialEq, Copy, Clone, Debug, Hash)] +#[repr(C)] +pub struct __BindgenOpaqueArray(pub [T; N]); +impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } +} #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Foo { - pub member: *mut [u8; 0usize], + pub member: *mut __BindgenOpaqueArray, } -pub type Foo_FirstAlias = [u8; 0usize]; -pub type Foo_SecondAlias = [u8; 0usize]; +pub type Foo_FirstAlias = __BindgenOpaqueArray; +pub type Foo_SecondAlias = __BindgenOpaqueArray; impl Default for Foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/win32-vectorcall-1_0.rs b/bindgen-tests/tests/expectations/tests/libclang-9/issue-753.rs similarity index 100% rename from bindgen-tests/tests/expectations/tests/win32-vectorcall-1_0.rs rename to bindgen-tests/tests/expectations/tests/libclang-9/issue-753.rs diff --git a/bindgen-tests/tests/expectations/tests/libclang-9/macro_fallback_non_system_dir.rs b/bindgen-tests/tests/expectations/tests/libclang-9/macro_fallback_non_system_dir.rs new file mode 100644 index 0000000000..8f5c4ba2da --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/libclang-9/macro_fallback_non_system_dir.rs @@ -0,0 +1 @@ +pub const NEGATIVE: i32 = -1; diff --git a/bindgen-tests/tests/expectations/tests/libclang-9/ptr32-has-different-size.rs b/bindgen-tests/tests/expectations/tests/libclang-9/ptr32-has-different-size.rs index 0d677052ea..f55f88f496 100644 --- a/bindgen-tests/tests/expectations/tests/libclang-9/ptr32-has-different-size.rs +++ b/bindgen-tests/tests/expectations/tests/libclang-9/ptr32-has-different-size.rs @@ -4,31 +4,14 @@ pub struct TEST_STRUCT { pub ptr_32bit: *mut ::std::os::raw::c_void, } -#[test] -fn bindgen_test_layout_TEST_STRUCT() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(TEST_STRUCT)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(TEST_STRUCT)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ptr_32bit) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(TEST_STRUCT), - "::", - stringify!(ptr_32bit), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TEST_STRUCT"][::std::mem::size_of::() - 8usize]; + ["Alignment of TEST_STRUCT"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: TEST_STRUCT::ptr_32bit", + ][::std::mem::offset_of!(TEST_STRUCT, ptr_32bit) - 0usize]; +}; impl Default for TEST_STRUCT { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/libclang-9/struct_typedef_ns.rs b/bindgen-tests/tests/expectations/tests/libclang-9/struct_typedef_ns.rs index 44afa4822a..d93a62e746 100644 --- a/bindgen-tests/tests/expectations/tests/libclang-9/struct_typedef_ns.rs +++ b/bindgen-tests/tests/expectations/tests/libclang-9/struct_typedef_ns.rs @@ -11,31 +11,16 @@ pub mod root { pub struct typedef_struct { pub foo: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_typedef_struct() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(typedef_struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(typedef_struct)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(typedef_struct), - "::", - stringify!(foo), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of typedef_struct"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of typedef_struct", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: typedef_struct::foo", + ][::std::mem::offset_of!(typedef_struct, foo) - 0usize]; + }; #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum typedef_enum { @@ -50,31 +35,16 @@ pub mod root { pub struct _bindgen_ty_1 { pub foo: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit<_bindgen_ty_1> = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::<_bindgen_ty_1>(), - 4usize, - concat!("Size of: ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::<_bindgen_ty_1>(), - 4usize, - concat!("Alignment of ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(_bindgen_ty_1), - "::", - stringify!(foo), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of _bindgen_ty_1"][::std::mem::size_of::<_bindgen_ty_1>() - 4usize]; + [ + "Alignment of _bindgen_ty_1", + ][::std::mem::align_of::<_bindgen_ty_1>() - 4usize]; + [ + "Offset of field: _bindgen_ty_1::foo", + ][::std::mem::offset_of!(_bindgen_ty_1, foo) - 0usize]; + }; pub type typedef_struct = root::_bindgen_mod_id_12::_bindgen_ty_1; pub const _bindgen_mod_id_12_BAR: root::_bindgen_mod_id_12::_bindgen_ty_2 = _bindgen_ty_2::BAR; #[repr(u32)] diff --git a/bindgen-tests/tests/expectations/tests/long_double.rs b/bindgen-tests/tests/expectations/tests/long_double.rs index b362787f9a..aa3109ca43 100644 --- a/bindgen-tests/tests/expectations/tests/long_double.rs +++ b/bindgen-tests/tests/expectations/tests/long_double.rs @@ -9,19 +9,11 @@ pub struct foo { fn bindgen_test_layout_foo() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(foo)), - ); + assert_eq!(::std::mem::size_of::(), 16usize, "Size of foo"); + assert_eq!(::std::mem::align_of::(), 16usize, "Alignment of foo"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), + "Offset of field: foo::bar", ); } diff --git a/bindgen-tests/tests/expectations/tests/macro-expr-uncommon-token.rs b/bindgen-tests/tests/expectations/tests/macro-expr-uncommon-token.rs index c905e5aa90..785ef4bb9f 100644 --- a/bindgen-tests/tests/expectations/tests/macro-expr-uncommon-token.rs +++ b/bindgen-tests/tests/expectations/tests/macro-expr-uncommon-token.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] pub const MODBUS_WOOT: u32 = 3; -extern "C" { +unsafe extern "C" { pub fn foo(); } diff --git a/bindgen-tests/tests/expectations/tests/macro_const_1_0.rs b/bindgen-tests/tests/expectations/tests/macro_const_1_0.rs deleted file mode 100644 index 2f3e228d80..0000000000 --- a/bindgen-tests/tests/expectations/tests/macro_const_1_0.rs +++ /dev/null @@ -1,8 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -pub const foo: &'static [u8; 4] = b"bar\0"; -pub const CHAR: u8 = 98u8; -pub const CHARR: u8 = 0u8; -pub const FLOAT: f64 = 5.09; -pub const FLOAT_EXPR: f64 = 0.005; -pub const LONG: u32 = 3; -pub const INVALID_UTF8: &'static [u8; 5] = b"\xF0(\x8C(\0"; diff --git a/bindgen-tests/tests/expectations/tests/mangling-ios.rs b/bindgen-tests/tests/expectations/tests/mangling-ios.rs index 05b7aecd3e..736d379f01 100644 --- a/bindgen-tests/tests/expectations/tests/mangling-ios.rs +++ b/bindgen-tests/tests/expectations/tests/mangling-ios.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(); } diff --git a/bindgen-tests/tests/expectations/tests/mangling-linux32.rs b/bindgen-tests/tests/expectations/tests/mangling-linux32.rs index 1672f2cf65..b6ed9146da 100644 --- a/bindgen-tests/tests/expectations/tests/mangling-linux32.rs +++ b/bindgen-tests/tests/expectations/tests/mangling-linux32.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(); } #[repr(C)] @@ -7,20 +7,12 @@ extern "C" { pub struct Foo { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo4sBarE"] pub static mut Foo_sBar: bool; } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/mangling-linux64.rs b/bindgen-tests/tests/expectations/tests/mangling-linux64.rs index 1672f2cf65..b6ed9146da 100644 --- a/bindgen-tests/tests/expectations/tests/mangling-linux64.rs +++ b/bindgen-tests/tests/expectations/tests/mangling-linux64.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(); } #[repr(C)] @@ -7,20 +7,12 @@ extern "C" { pub struct Foo { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo4sBarE"] pub static mut Foo_sBar: bool; } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/mangling-macos.rs b/bindgen-tests/tests/expectations/tests/mangling-macos.rs index b3c236bb0b..237859e23b 100644 --- a/bindgen-tests/tests/expectations/tests/mangling-macos.rs +++ b/bindgen-tests/tests/expectations/tests/mangling-macos.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(); } #[repr(C)] @@ -7,20 +7,12 @@ extern "C" { pub struct Foo { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}__ZN3Foo4sBarE"] pub static mut Foo_sBar: bool; } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/mangling-win32.rs b/bindgen-tests/tests/expectations/tests/mangling-win32.rs index 34efb92461..263f619374 100644 --- a/bindgen-tests/tests/expectations/tests/mangling-win32.rs +++ b/bindgen-tests/tests/expectations/tests/mangling-win32.rs @@ -1,5 +1,6 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +#![cfg(target = "i686-pc-windows-msvc")] +unsafe extern "C" { pub fn foo(); } #[repr(C)] @@ -7,37 +8,29 @@ extern "C" { pub struct Foo { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}?sBar@Foo@@2_NA"] pub static mut Foo_sBar: bool; } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "fastcall" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "fastcall" { pub fn fast_call_func_no_args() -> ::std::os::raw::c_int; } -extern "fastcall" { +unsafe extern "fastcall" { pub fn fast_call_func_many_args( arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int; } -extern "stdcall" { +unsafe extern "stdcall" { pub fn std_call_func_no_args() -> ::std::os::raw::c_int; } -extern "stdcall" { +unsafe extern "stdcall" { pub fn std_call_func_many_args( arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, diff --git a/bindgen-tests/tests/expectations/tests/mangling-win64.rs b/bindgen-tests/tests/expectations/tests/mangling-win64.rs index 99224e54dc..2a782480ed 100644 --- a/bindgen-tests/tests/expectations/tests/mangling-win64.rs +++ b/bindgen-tests/tests/expectations/tests/mangling-win64.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(); } #[repr(C)] @@ -7,20 +7,12 @@ extern "C" { pub struct Foo { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}?sBar@Foo@@2_NA"] pub static mut Foo_sBar: bool; } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/merge-extern-blocks.rs b/bindgen-tests/tests/expectations/tests/merge-extern-blocks.rs deleted file mode 100644 index 5c4b8e02ae..0000000000 --- a/bindgen-tests/tests/expectations/tests/merge-extern-blocks.rs +++ /dev/null @@ -1,72 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] -pub mod root { - #[allow(unused_imports)] - use self::super::root; - #[repr(C)] - #[derive(Debug, Default, Copy, Clone)] - pub struct Point { - pub x: ::std::os::raw::c_int, - } - #[test] - fn bindgen_test_layout_Point() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Point)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Point)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Point), "::", stringify!(x)), - ); - } - pub mod ns { - #[allow(unused_imports)] - use self::super::super::root; - #[repr(C)] - #[derive(Debug, Default, Copy, Clone)] - pub struct Point { - pub x: ::std::os::raw::c_int, - } - #[test] - fn bindgen_test_layout_Point() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Point)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Point)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Point), "::", stringify!(x)), - ); - } - extern "C" { - #[link_name = "\u{1}_ZN2ns3fooEv"] - pub fn foo() -> ::std::os::raw::c_int; - #[link_name = "\u{1}_ZN2ns3barEv"] - pub fn bar() -> ::std::os::raw::c_int; - } - } - extern "C" { - #[link_name = "\u{1}_Z3foov"] - pub fn foo() -> ::std::os::raw::c_int; - #[link_name = "\u{1}_Z3barv"] - pub fn bar() -> ::std::os::raw::c_int; - } -} diff --git a/bindgen-tests/tests/expectations/tests/merge_extern_blocks_post_1_82.rs b/bindgen-tests/tests/expectations/tests/merge_extern_blocks_post_1_82.rs new file mode 100644 index 0000000000..98659f6382 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/merge_extern_blocks_post_1_82.rs @@ -0,0 +1,44 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub mod root { + #[allow(unused_imports)] + use self::super::root; + #[repr(C)] + #[derive(Debug, Default, Copy, Clone)] + pub struct Point { + pub x: ::std::os::raw::c_int, + } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Point"][::std::mem::size_of::() - 4usize]; + ["Alignment of Point"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Point::x"][::std::mem::offset_of!(Point, x) - 0usize]; + }; + pub mod ns { + #[allow(unused_imports)] + use self::super::super::root; + #[repr(C)] + #[derive(Debug, Default, Copy, Clone)] + pub struct Point { + pub x: ::std::os::raw::c_int, + } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Point"][::std::mem::size_of::() - 4usize]; + ["Alignment of Point"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Point::x"][::std::mem::offset_of!(Point, x) - 0usize]; + }; + unsafe extern "C" { + #[link_name = "\u{1}_ZN2ns3fooEv"] + pub fn foo() -> ::std::os::raw::c_int; + #[link_name = "\u{1}_ZN2ns3barEv"] + pub fn bar() -> ::std::os::raw::c_int; + } + } + unsafe extern "C" { + #[link_name = "\u{1}_Z3foov"] + pub fn foo() -> ::std::os::raw::c_int; + #[link_name = "\u{1}_Z3barv"] + pub fn bar() -> ::std::os::raw::c_int; + } +} diff --git a/bindgen-tests/tests/expectations/tests/merge_extern_blocks_pre_1_82.rs b/bindgen-tests/tests/expectations/tests/merge_extern_blocks_pre_1_82.rs new file mode 100644 index 0000000000..595d865af1 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/merge_extern_blocks_pre_1_82.rs @@ -0,0 +1,44 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub mod root { + #[allow(unused_imports)] + use self::super::root; + #[repr(C)] + #[derive(Debug, Default, Copy, Clone)] + pub struct Point { + pub x: ::std::os::raw::c_int, + } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Point"][::std::mem::size_of::() - 4usize]; + ["Alignment of Point"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Point::x"][::std::mem::offset_of!(Point, x) - 0usize]; + }; + pub mod ns { + #[allow(unused_imports)] + use self::super::super::root; + #[repr(C)] + #[derive(Debug, Default, Copy, Clone)] + pub struct Point { + pub x: ::std::os::raw::c_int, + } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Point"][::std::mem::size_of::() - 4usize]; + ["Alignment of Point"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Point::x"][::std::mem::offset_of!(Point, x) - 0usize]; + }; + extern "C" { + #[link_name = "\u{1}_ZN2ns3fooEv"] + pub fn foo() -> ::std::os::raw::c_int; + #[link_name = "\u{1}_ZN2ns3barEv"] + pub fn bar() -> ::std::os::raw::c_int; + } + } + extern "C" { + #[link_name = "\u{1}_Z3foov"] + pub fn foo() -> ::std::os::raw::c_int; + #[link_name = "\u{1}_Z3barv"] + pub fn bar() -> ::std::os::raw::c_int; + } +} diff --git a/bindgen-tests/tests/expectations/tests/method-mangling.rs b/bindgen-tests/tests/expectations/tests/method-mangling.rs index f241f43525..4c86825cce 100644 --- a/bindgen-tests/tests/expectations/tests/method-mangling.rs +++ b/bindgen-tests/tests/expectations/tests/method-mangling.rs @@ -4,20 +4,12 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3Foo4typeEv"] pub fn Foo_type(this: *mut Foo) -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/module-allowlisted.rs b/bindgen-tests/tests/expectations/tests/module-allowlisted.rs index 945bccac2d..9ac408dc8f 100644 --- a/bindgen-tests/tests/expectations/tests/module-allowlisted.rs +++ b/bindgen-tests/tests/expectations/tests/module-allowlisted.rs @@ -8,17 +8,9 @@ pub mod root { pub struct Test { pub _address: u8, } - #[test] - fn bindgen_test_layout_Test() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Test)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Test"][::std::mem::size_of::() - 1usize]; + ["Alignment of Test"][::std::mem::align_of::() - 1usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/msvc-no-usr.rs b/bindgen-tests/tests/expectations/tests/msvc-no-usr.rs index 2afd183321..adaa1a07b2 100644 --- a/bindgen-tests/tests/expectations/tests/msvc-no-usr.rs +++ b/bindgen-tests/tests/expectations/tests/msvc-no-usr.rs @@ -4,19 +4,9 @@ pub struct A { pub foo: usize, } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 8usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 8usize]; + ["Alignment of A"][::std::mem::align_of::() - 8usize]; + ["Offset of field: A::foo"][::std::mem::offset_of!(A, foo) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/multiple-inherit-empty-correct-layout.rs b/bindgen-tests/tests/expectations/tests/multiple-inherit-empty-correct-layout.rs index 81b5e7f1d8..b0cf27451c 100644 --- a/bindgen-tests/tests/expectations/tests/multiple-inherit-empty-correct-layout.rs +++ b/bindgen-tests/tests/expectations/tests/multiple-inherit-empty-correct-layout.rs @@ -4,52 +4,28 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Bar { pub _address: u8, } -#[test] -fn bindgen_test_layout_Bar() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Baz { pub _address: u8, } -#[test] -fn bindgen_test_layout_Baz() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Baz"][::std::mem::size_of::() - 1usize]; + ["Alignment of Baz"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/mutable.rs b/bindgen-tests/tests/expectations/tests/mutable.rs index ddf49aaeee..ff98d31f24 100644 --- a/bindgen-tests/tests/expectations/tests/mutable.rs +++ b/bindgen-tests/tests/expectations/tests/mutable.rs @@ -5,79 +5,41 @@ pub struct C { pub m_member: ::std::os::raw::c_int, pub m_other: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 8usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m_member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(m_member)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m_other) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(m_other)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 8usize]; + ["Alignment of C"][::std::mem::align_of::() - 4usize]; + ["Offset of field: C::m_member"][::std::mem::offset_of!(C, m_member) - 0usize]; + ["Offset of field: C::m_other"][::std::mem::offset_of!(C, m_other) - 4usize]; +}; #[repr(C)] #[derive(Debug, Default)] pub struct NonCopiable { pub m_member: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_NonCopiable() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NonCopiable)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NonCopiable)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m_member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(NonCopiable), "::", stringify!(m_member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NonCopiable"][::std::mem::size_of::() - 4usize]; + ["Alignment of NonCopiable"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: NonCopiable::m_member", + ][::std::mem::offset_of!(NonCopiable, m_member) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default)] pub struct NonCopiableWithNonCopiableMutableMember { pub m_member: NonCopiable, } -#[test] -fn bindgen_test_layout_NonCopiableWithNonCopiableMutableMember() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NonCopiableWithNonCopiableMutableMember)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NonCopiableWithNonCopiableMutableMember)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m_member) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(NonCopiableWithNonCopiableMutableMember), - "::", - stringify!(m_member), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of NonCopiableWithNonCopiableMutableMember", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of NonCopiableWithNonCopiableMutableMember", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: NonCopiableWithNonCopiableMutableMember::m_member", + ][::std::mem::offset_of!(NonCopiableWithNonCopiableMutableMember, m_member) + - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/namespace.rs b/bindgen-tests/tests/expectations/tests/namespace.rs index ebeccb1344..4e58fa7ab1 100644 --- a/bindgen-tests/tests/expectations/tests/namespace.rs +++ b/bindgen-tests/tests/expectations/tests/namespace.rs @@ -3,7 +3,7 @@ pub mod root { #[allow(unused_imports)] use self::super::root; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_Z9top_levelv"] pub fn top_level(); } @@ -12,7 +12,7 @@ pub mod root { use self::super::super::root; pub type whatever_other_thing_t = whatever_int_t; pub type whatever_int_t = ::std::os::raw::c_int; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN8whatever11in_whateverEv"] pub fn in_whatever(); } @@ -25,35 +25,21 @@ pub mod root { pub struct A { pub b: root::whatever::whatever_int_t, } - #[test] - fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(A)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(b)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of A"][::std::mem::size_of::() - 4usize]; + ["Alignment of A"][::std::mem::align_of::() - 4usize]; + ["Offset of field: A::b"][::std::mem::offset_of!(A, b) - 0usize]; + }; } #[repr(C)] #[derive(Debug)] pub struct C { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _base: root::_bindgen_mod_id_17::A, pub m_c: T, pub m_c_ptr: *mut T, pub m_c_arr: [T; 10usize], - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for C { fn default() -> Self { @@ -71,8 +57,8 @@ pub mod root { #[repr(C)] #[derive(Debug)] pub struct D { - pub m_c: root::C, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub m_c: root::C, } impl Default for D { fn default() -> Self { @@ -83,15 +69,15 @@ pub mod root { } } } - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN1w3hehEv"] pub fn heh() -> root::w::whatever_int_t; } - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN1w3fooEv"] pub fn foo() -> root::C<::std::os::raw::c_int>; } - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN1w4barrEv"] pub fn barr() -> root::C; } @@ -99,7 +85,7 @@ pub mod root { pub mod foobar { #[allow(unused_imports)] use self::super::super::root; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN6foobar3fooEv"] pub fn foo(); } @@ -107,7 +93,7 @@ pub mod root { pub mod faraway { #[allow(unused_imports)] use self::super::super::root; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN7faraway3barEv"] pub fn bar(); } diff --git a/bindgen-tests/tests/expectations/tests/nested.rs b/bindgen-tests/tests/expectations/tests/nested.rs index 71d3a4c28a..5e0a8b07c8 100644 --- a/bindgen-tests/tests/expectations/tests/nested.rs +++ b/bindgen-tests/tests/expectations/tests/nested.rs @@ -4,26 +4,12 @@ pub struct Calc { pub w: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Calc() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Calc)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Calc)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).w) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Calc), "::", stringify!(w)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Calc"][::std::mem::size_of::() - 4usize]; + ["Alignment of Calc"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Calc::w"][::std::mem::offset_of!(Calc, w) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Test { @@ -40,54 +26,28 @@ pub struct Test_Size { pub struct Test_Size_Dimension { pub _base: Calc, } -#[test] -fn bindgen_test_layout_Test_Size_Dimension() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Test_Size_Dimension)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Test_Size_Dimension)), - ); -} -#[test] -fn bindgen_test_layout_Test_Size() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Test_Size)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Test_Size)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mWidth) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test_Size), "::", stringify!(mWidth)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mHeight) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Test_Size), "::", stringify!(mHeight)), - ); -} -#[test] -fn bindgen_test_layout_Test() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Test)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of Test_Size_Dimension", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of Test_Size_Dimension", + ][::std::mem::align_of::() - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test_Size"][::std::mem::size_of::() - 8usize]; + ["Alignment of Test_Size"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: Test_Size::mWidth", + ][::std::mem::offset_of!(Test_Size, mWidth) - 0usize]; + [ + "Offset of field: Test_Size::mHeight", + ][::std::mem::offset_of!(Test_Size, mHeight) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 1usize]; + ["Alignment of Test"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/nested_vtable.rs b/bindgen-tests/tests/expectations/tests/nested_vtable.rs index bcedd777e8..12aa2ea441 100644 --- a/bindgen-tests/tests/expectations/tests/nested_vtable.rs +++ b/bindgen-tests/tests/expectations/tests/nested_vtable.rs @@ -10,19 +10,11 @@ pub struct nsISupports__bindgen_vtable { pub struct nsISupports { pub vtable_: *const nsISupports__bindgen_vtable, } -#[test] -fn bindgen_test_layout_nsISupports() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsISupports)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsISupports)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of nsISupports"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsISupports"][::std::mem::align_of::() - 8usize]; +}; impl Default for nsISupports { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -32,7 +24,7 @@ impl Default for nsISupports { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN11nsISupports14QueryInterfaceEv"] pub fn nsISupports_QueryInterface( this: *mut ::std::os::raw::c_void, @@ -43,19 +35,11 @@ extern "C" { pub struct nsIRunnable { pub _base: nsISupports, } -#[test] -fn bindgen_test_layout_nsIRunnable() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsIRunnable)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsIRunnable)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of nsIRunnable"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsIRunnable"][::std::mem::align_of::() - 8usize]; +}; impl Default for nsIRunnable { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -70,19 +54,11 @@ impl Default for nsIRunnable { pub struct Runnable { pub _base: nsIRunnable, } -#[test] -fn bindgen_test_layout_Runnable() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Runnable)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Runnable)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Runnable"][::std::mem::size_of::() - 8usize]; + ["Alignment of Runnable"][::std::mem::align_of::() - 8usize]; +}; impl Default for Runnable { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/nested_within_namespace.rs b/bindgen-tests/tests/expectations/tests/nested_within_namespace.rs index c9b00d5add..f470571ddc 100644 --- a/bindgen-tests/tests/expectations/tests/nested_within_namespace.rs +++ b/bindgen-tests/tests/expectations/tests/nested_within_namespace.rs @@ -16,70 +16,30 @@ pub mod root { pub struct Bar_Baz { pub foo: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_Bar_Baz() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar_Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar_Baz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar_Baz), "::", stringify!(foo)), - ); - } - #[test] - fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(foo)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Bar_Baz"][::std::mem::size_of::() - 4usize]; + ["Alignment of Bar_Baz"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: Bar_Baz::foo", + ][::std::mem::offset_of!(Bar_Baz, foo) - 0usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Bar::foo"][::std::mem::offset_of!(Bar, foo) - 0usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Baz { pub baz: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_Baz() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Baz)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Baz), "::", stringify!(baz)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Baz"][::std::mem::size_of::() - 4usize]; + ["Alignment of Baz"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Baz::baz"][::std::mem::offset_of!(Baz, baz) - 0usize]; + }; } } diff --git a/bindgen-tests/tests/expectations/tests/newtype-enum.rs b/bindgen-tests/tests/expectations/tests/newtype-enum.rs index ea25950de0..0045c52a61 100644 --- a/bindgen-tests/tests/expectations/tests/newtype-enum.rs +++ b/bindgen-tests/tests/expectations/tests/newtype-enum.rs @@ -1,14 +1,8 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] impl Foo { pub const Bar: Foo = Foo(2); -} -impl Foo { pub const Baz: Foo = Foo(4); -} -impl Foo { pub const Duplicated: Foo = Foo(4); -} -impl Foo { pub const Negative: Foo = Foo(-3); } #[repr(transparent)] diff --git a/bindgen-tests/tests/expectations/tests/no-comments.rs b/bindgen-tests/tests/expectations/tests/no-comments.rs index 712580c9fd..6a60973fb4 100644 --- a/bindgen-tests/tests/expectations/tests/no-comments.rs +++ b/bindgen-tests/tests/expectations/tests/no-comments.rs @@ -4,23 +4,9 @@ pub struct Foo { pub s: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).s) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(s)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Foo::s"][::std::mem::offset_of!(Foo, s) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no-derive-debug.rs b/bindgen-tests/tests/expectations/tests/no-derive-debug.rs index 6a8c4d8aa7..5e525068fd 100644 --- a/bindgen-tests/tests/expectations/tests/no-derive-debug.rs +++ b/bindgen-tests/tests/expectations/tests/no-derive-debug.rs @@ -12,31 +12,13 @@ pub struct bar { pub foo: foo, pub baz: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: bar::foo"][::std::mem::offset_of!(bar, foo) - 0usize]; + ["Offset of field: bar::baz"][::std::mem::offset_of!(bar, baz) - 4usize]; +}; impl Default for bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/no-derive-default.rs b/bindgen-tests/tests/expectations/tests/no-derive-default.rs index fea25bec1e..a1d86a6502 100644 --- a/bindgen-tests/tests/expectations/tests/no-derive-default.rs +++ b/bindgen-tests/tests/expectations/tests/no-derive-default.rs @@ -12,28 +12,10 @@ pub struct bar { pub foo: foo, pub baz: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: bar::foo"][::std::mem::offset_of!(bar, foo) - 0usize]; + ["Offset of field: bar::baz"][::std::mem::offset_of!(bar, baz) - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no-hash-allowlisted.rs b/bindgen-tests/tests/expectations/tests/no-hash-allowlisted.rs index ab94a578d8..ff4dd1e38e 100644 --- a/bindgen-tests/tests/expectations/tests/no-hash-allowlisted.rs +++ b/bindgen-tests/tests/expectations/tests/no-hash-allowlisted.rs @@ -4,23 +4,9 @@ pub struct NoHash { pub i: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_NoHash() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoHash)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoHash)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(NoHash), "::", stringify!(i)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoHash"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoHash"][::std::mem::align_of::() - 4usize]; + ["Offset of field: NoHash::i"][::std::mem::offset_of!(NoHash, i) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no-hash-opaque.rs b/bindgen-tests/tests/expectations/tests/no-hash-opaque.rs index 9f25d948a5..9dc9e01989 100644 --- a/bindgen-tests/tests/expectations/tests/no-hash-opaque.rs +++ b/bindgen-tests/tests/expectations/tests/no-hash-opaque.rs @@ -5,16 +5,8 @@ pub struct NoHash { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_NoHash() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoHash)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoHash)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoHash"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoHash"][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no-partialeq-allowlisted.rs b/bindgen-tests/tests/expectations/tests/no-partialeq-allowlisted.rs index d07f16b944..68ae1a7449 100644 --- a/bindgen-tests/tests/expectations/tests/no-partialeq-allowlisted.rs +++ b/bindgen-tests/tests/expectations/tests/no-partialeq-allowlisted.rs @@ -4,23 +4,9 @@ pub struct NoPartialEq { pub i: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_NoPartialEq() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoPartialEq)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoPartialEq)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(NoPartialEq), "::", stringify!(i)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoPartialEq"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoPartialEq"][::std::mem::align_of::() - 4usize]; + ["Offset of field: NoPartialEq::i"][::std::mem::offset_of!(NoPartialEq, i) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no-partialeq-opaque.rs b/bindgen-tests/tests/expectations/tests/no-partialeq-opaque.rs index cf775ccd47..4b488df6a5 100644 --- a/bindgen-tests/tests/expectations/tests/no-partialeq-opaque.rs +++ b/bindgen-tests/tests/expectations/tests/no-partialeq-opaque.rs @@ -5,16 +5,8 @@ pub struct NoPartialEq { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_NoPartialEq() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoPartialEq)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoPartialEq)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoPartialEq"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoPartialEq"][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no-recursive-allowlisting.rs b/bindgen-tests/tests/expectations/tests/no-recursive-allowlisting.rs index 6dd354df35..dc1e4721ab 100644 --- a/bindgen-tests/tests/expectations/tests/no-recursive-allowlisting.rs +++ b/bindgen-tests/tests/expectations/tests/no-recursive-allowlisting.rs @@ -5,26 +5,12 @@ pub enum Bar {} pub struct Foo { pub baz: *mut Bar, } -#[test] -fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Foo::baz"][::std::mem::offset_of!(Foo, baz) - 0usize]; +}; impl Default for Foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/no-std.rs b/bindgen-tests/tests/expectations/tests/no-std.rs index a41bef8939..0f03c222ef 100644 --- a/bindgen-tests/tests/expectations/tests/no-std.rs +++ b/bindgen-tests/tests/expectations/tests/no-std.rs @@ -11,36 +11,14 @@ pub struct foo { pub b: libc::c_int, pub bar: *mut libc::c_void, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::core::mem::MaybeUninit = ::core::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::core::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::core::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::core::mem::size_of::() - 16usize]; + ["Alignment of foo"][::core::mem::align_of::() - 8usize]; + ["Offset of field: foo::a"][::core::mem::offset_of!(foo, a) - 0usize]; + ["Offset of field: foo::b"][::core::mem::offset_of!(foo, b) - 4usize]; + ["Offset of field: foo::bar"][::core::mem::offset_of!(foo, bar) - 8usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::core::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/no_copy_allowlisted.rs b/bindgen-tests/tests/expectations/tests/no_copy_allowlisted.rs index b0c9bc026e..67be391799 100644 --- a/bindgen-tests/tests/expectations/tests/no_copy_allowlisted.rs +++ b/bindgen-tests/tests/expectations/tests/no_copy_allowlisted.rs @@ -4,23 +4,9 @@ pub struct NoCopy { pub i: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_NoCopy() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoCopy)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoCopy)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(NoCopy), "::", stringify!(i)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoCopy"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoCopy"][::std::mem::align_of::() - 4usize]; + ["Offset of field: NoCopy::i"][::std::mem::offset_of!(NoCopy, i) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no_copy_opaque.rs b/bindgen-tests/tests/expectations/tests/no_copy_opaque.rs index 3a8f84784d..dea6a0a6cf 100644 --- a/bindgen-tests/tests/expectations/tests/no_copy_opaque.rs +++ b/bindgen-tests/tests/expectations/tests/no_copy_opaque.rs @@ -5,16 +5,8 @@ pub struct NoCopy { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_NoCopy() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoCopy)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoCopy)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoCopy"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoCopy"][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no_debug_allowlisted.rs b/bindgen-tests/tests/expectations/tests/no_debug_allowlisted.rs index e58f9bf85a..1ddb20a747 100644 --- a/bindgen-tests/tests/expectations/tests/no_debug_allowlisted.rs +++ b/bindgen-tests/tests/expectations/tests/no_debug_allowlisted.rs @@ -4,23 +4,9 @@ pub struct NoDebug { pub i: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_NoDebug() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoDebug)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoDebug)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(NoDebug), "::", stringify!(i)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoDebug"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoDebug"][::std::mem::align_of::() - 4usize]; + ["Offset of field: NoDebug::i"][::std::mem::offset_of!(NoDebug, i) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no_debug_bypass_impl_debug.rs b/bindgen-tests/tests/expectations/tests/no_debug_bypass_impl_debug.rs index 7078a4c255..d972c74376 100644 --- a/bindgen-tests/tests/expectations/tests/no_debug_bypass_impl_debug.rs +++ b/bindgen-tests/tests/expectations/tests/no_debug_bypass_impl_debug.rs @@ -1,8 +1,8 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #[repr(C)] pub struct Generic { - pub t: [T; 40usize], pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: [T; 40usize], } impl Default for Generic { fn default() -> Self { @@ -20,8 +20,8 @@ impl ::std::fmt::Debug for Generic { } #[repr(C)] pub struct NoDebug { - pub t: [T; 40usize], pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: [T; 40usize], } impl Default for NoDebug { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/no_debug_opaque.rs b/bindgen-tests/tests/expectations/tests/no_debug_opaque.rs index 527d370103..0bb37ec711 100644 --- a/bindgen-tests/tests/expectations/tests/no_debug_opaque.rs +++ b/bindgen-tests/tests/expectations/tests/no_debug_opaque.rs @@ -5,16 +5,8 @@ pub struct NoDebug { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_NoDebug() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoDebug)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoDebug)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoDebug"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoDebug"][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no_default_allowlisted.rs b/bindgen-tests/tests/expectations/tests/no_default_allowlisted.rs index 55501ebd2b..593e644343 100644 --- a/bindgen-tests/tests/expectations/tests/no_default_allowlisted.rs +++ b/bindgen-tests/tests/expectations/tests/no_default_allowlisted.rs @@ -4,23 +4,9 @@ pub struct NoDefault { pub i: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_NoDefault() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoDefault)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoDefault)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(NoDefault), "::", stringify!(i)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoDefault"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoDefault"][::std::mem::align_of::() - 4usize]; + ["Offset of field: NoDefault::i"][::std::mem::offset_of!(NoDefault, i) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no_default_bypass_derive_default.rs b/bindgen-tests/tests/expectations/tests/no_default_bypass_derive_default.rs index f5b4322065..58f3684ac9 100644 --- a/bindgen-tests/tests/expectations/tests/no_default_bypass_derive_default.rs +++ b/bindgen-tests/tests/expectations/tests/no_default_bypass_derive_default.rs @@ -1,8 +1,8 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #[repr(C)] pub struct Generic { - pub t: [T; 40usize], pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: [T; 40usize], } impl Default for Generic { fn default() -> Self { @@ -15,6 +15,6 @@ impl Default for Generic { } #[repr(C)] pub struct NoDefault { - pub t: [T; 40usize], pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: [T; 40usize], } diff --git a/bindgen-tests/tests/expectations/tests/no_default_opaque.rs b/bindgen-tests/tests/expectations/tests/no_default_opaque.rs index b7dd4d41e1..ba2f63f91c 100644 --- a/bindgen-tests/tests/expectations/tests/no_default_opaque.rs +++ b/bindgen-tests/tests/expectations/tests/no_default_opaque.rs @@ -5,16 +5,8 @@ pub struct NoDefault { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_NoDefault() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NoDefault)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NoDefault)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NoDefault"][::std::mem::size_of::() - 4usize]; + ["Alignment of NoDefault"][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/no_size_t_is_usize.rs b/bindgen-tests/tests/expectations/tests/no_size_t_is_usize.rs index 99d13449c7..94ce735b31 100644 --- a/bindgen-tests/tests/expectations/tests/no_size_t_is_usize.rs +++ b/bindgen-tests/tests/expectations/tests/no_size_t_is_usize.rs @@ -8,32 +8,14 @@ pub struct A { pub offset: ssize_t, pub next: *mut A, } -#[test] -fn bindgen_test_layout_A() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 24usize, concat!("Size of: ", stringify!(A))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(A)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).len) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(len)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).offset) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(offset)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).next) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(A), "::", stringify!(next)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 24usize]; + ["Alignment of A"][::std::mem::align_of::() - 8usize]; + ["Offset of field: A::len"][::std::mem::offset_of!(A, len) - 0usize]; + ["Offset of field: A::offset"][::std::mem::offset_of!(A, offset) - 8usize]; + ["Offset of field: A::next"][::std::mem::offset_of!(A, next) - 16usize]; +}; impl Default for A { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/non-type-params.rs b/bindgen-tests/tests/expectations/tests/non-type-params.rs index e83ee74de6..afd21fb767 100644 --- a/bindgen-tests/tests/expectations/tests/non-type-params.rs +++ b/bindgen-tests/tests/expectations/tests/non-type-params.rs @@ -1,55 +1,34 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +/// If Bindgen could only determine the size and alignment of a +/// type, it is represented like this. +#[derive(PartialEq, Copy, Clone, Debug, Hash)] +#[repr(C)] +pub struct __BindgenOpaqueArray(pub [T; N]); +impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } +} pub type Array16 = u8; -pub type ArrayInt4 = [u32; 4usize]; +pub type ArrayInt4 = __BindgenOpaqueArray; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct UsesArray { - pub array_char_16: [u8; 16usize], - pub array_bool_8: [u8; 8usize], + pub array_char_16: __BindgenOpaqueArray, + pub array_bool_8: __BindgenOpaqueArray, pub array_int_4: ArrayInt4, } -#[test] -fn bindgen_test_layout_UsesArray() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 40usize, - concat!("Size of: ", stringify!(UsesArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(UsesArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).array_char_16) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(UsesArray), - "::", - stringify!(array_char_16), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).array_bool_8) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(UsesArray), - "::", - stringify!(array_bool_8), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).array_int_4) as usize - ptr as usize }, - 24usize, - concat!( - "Offset of field: ", - stringify!(UsesArray), - "::", - stringify!(array_int_4), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of UsesArray"][::std::mem::size_of::() - 40usize]; + ["Alignment of UsesArray"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: UsesArray::array_char_16", + ][::std::mem::offset_of!(UsesArray, array_char_16) - 0usize]; + [ + "Offset of field: UsesArray::array_bool_8", + ][::std::mem::offset_of!(UsesArray, array_bool_8) - 16usize]; + [ + "Offset of field: UsesArray::array_int_4", + ][::std::mem::offset_of!(UsesArray, array_int_4) - 24usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/noreturn.rs b/bindgen-tests/tests/expectations/tests/noreturn.rs index 2081d3d44b..0e601b5510 100644 --- a/bindgen-tests/tests/expectations/tests/noreturn.rs +++ b/bindgen-tests/tests/expectations/tests/noreturn.rs @@ -1,21 +1,21 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z1fv"] pub fn f() -> !; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z1gv"] pub fn g() -> !; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z1hv"] pub fn h() -> !; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z1iPFvvE"] pub fn i(arg: ::std::option::Option !>); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z1jPFvvE"] pub fn j(arg: ::std::option::Option !>) -> !; } diff --git a/bindgen-tests/tests/expectations/tests/nsBaseHashtable.rs b/bindgen-tests/tests/expectations/tests/nsBaseHashtable.rs index f2f7eefb46..32fcc37aba 100644 --- a/bindgen-tests/tests/expectations/tests/nsBaseHashtable.rs +++ b/bindgen-tests/tests/expectations/tests/nsBaseHashtable.rs @@ -1,4 +1,14 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +/// If Bindgen could only determine the size and alignment of a +/// type, it is represented like this. +#[derive(PartialEq, Copy, Clone, Debug, Hash)] +#[repr(C)] +pub struct __BindgenOpaqueArray(pub [T; N]); +impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } +} #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct nsBaseHashtableET { @@ -14,7 +24,7 @@ pub struct nsTHashtable { pub struct nsBaseHashtable { pub _address: u8, } -pub type nsBaseHashtable_KeyType = [u8; 0usize]; +pub type nsBaseHashtable_KeyType = __BindgenOpaqueArray; pub type nsBaseHashtable_EntryType = nsBaseHashtableET; #[repr(C)] #[derive(Debug, Copy, Clone)] diff --git a/bindgen-tests/tests/expectations/tests/nsStyleAutoArray.rs b/bindgen-tests/tests/expectations/tests/nsStyleAutoArray.rs index b475b1a9b1..3d8edcfdc1 100644 --- a/bindgen-tests/tests/expectations/tests/nsStyleAutoArray.rs +++ b/bindgen-tests/tests/expectations/tests/nsStyleAutoArray.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsTArray { - pub mBuff: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub mBuff: *mut T, } impl Default for nsTArray { fn default() -> Self { @@ -17,9 +17,9 @@ impl Default for nsTArray { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsStyleAutoArray { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub mFirstElement: T, pub mOtherElements: nsTArray, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } #[repr(i32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] diff --git a/bindgen-tests/tests/expectations/tests/objc_class.rs b/bindgen-tests/tests/expectations/tests/objc_class.rs index 50bdea53ee..a7346d1ee9 100644 --- a/bindgen-tests/tests/expectations/tests/objc_class.rs +++ b/bindgen-tests/tests/expectations/tests/objc_class.rs @@ -3,7 +3,7 @@ use objc::{self, msg_send, sel, sel_impl, class}; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; -extern "C" { +unsafe extern "C" { pub static mut fooVar: Foo; } #[repr(transparent)] diff --git a/bindgen-tests/tests/expectations/tests/objc_interface_type.rs b/bindgen-tests/tests/expectations/tests/objc_interface_type.rs index a49f9229a0..56ad75ed25 100644 --- a/bindgen-tests/tests/expectations/tests/objc_interface_type.rs +++ b/bindgen-tests/tests/expectations/tests/objc_interface_type.rs @@ -25,26 +25,12 @@ pub trait IFoo: Sized + std::ops::Deref {} pub struct FooStruct { pub foo: Foo, } -#[test] -fn bindgen_test_layout_FooStruct() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(FooStruct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(FooStruct)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(FooStruct), "::", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of FooStruct"][::std::mem::size_of::() - 8usize]; + ["Alignment of FooStruct"][::std::mem::align_of::() - 8usize]; + ["Offset of field: FooStruct::foo"][::std::mem::offset_of!(FooStruct, foo) - 0usize]; +}; impl Default for FooStruct { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -54,9 +40,9 @@ impl Default for FooStruct { } } } -extern "C" { +unsafe extern "C" { pub fn fooFunc(foo: Foo); } -extern "C" { +unsafe extern "C" { pub static mut kFoo: Foo; } diff --git a/bindgen-tests/tests/expectations/tests/objc_sel_and_id.rs b/bindgen-tests/tests/expectations/tests/objc_sel_and_id.rs index 25854d8488..cf38af4e64 100644 --- a/bindgen-tests/tests/expectations/tests/objc_sel_and_id.rs +++ b/bindgen-tests/tests/expectations/tests/objc_sel_and_id.rs @@ -3,12 +3,12 @@ use objc::{self, msg_send, sel, sel_impl, class}; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; -extern "C" { +unsafe extern "C" { pub static mut object: id; } -extern "C" { +unsafe extern "C" { pub static mut selector: objc::runtime::Sel; } -extern "C" { +unsafe extern "C" { pub fn f(object: id, selector: objc::runtime::Sel); } diff --git a/bindgen-tests/tests/expectations/tests/only_bitfields.rs b/bindgen-tests/tests/expectations/tests/only_bitfields.rs index fe216f4b56..3aedce1e3f 100644 --- a/bindgen-tests/tests/expectations/tests/only_bitfields.rs +++ b/bindgen-tests/tests/expectations/tests/only_bitfields.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -89,15 +151,11 @@ pub struct C { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, } -#[test] -fn bindgen_test_layout_C() { - assert_eq!(::std::mem::size_of::(), 1usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(C)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 1usize]; + ["Alignment of C"][::std::mem::align_of::() - 1usize]; +}; impl C { #[inline] pub fn a(&self) -> bool { @@ -111,6 +169,30 @@ impl C { } } #[inline] + pub unsafe fn a_raw(this: *const Self) -> bool { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b(&self) -> bool { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 7u8) as u8) } } @@ -122,6 +204,30 @@ impl C { } } #[inline] + pub unsafe fn b_raw(this: *const Self) -> bool { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 7u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 7u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1(a: bool, b: bool) -> __BindgenBitfieldUnit<[u8; 1usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); __bindgen_bitfield_unit diff --git a/bindgen-tests/tests/expectations/tests/opaque-template-inst-member-2.rs b/bindgen-tests/tests/expectations/tests/opaque-template-inst-member-2.rs index 3dd89d0a5d..14718a9312 100644 --- a/bindgen-tests/tests/expectations/tests/opaque-template-inst-member-2.rs +++ b/bindgen-tests/tests/expectations/tests/opaque-template-inst-member-2.rs @@ -13,41 +13,21 @@ pub struct ContainsOpaqueTemplate { pub mBlah: u32, pub mBaz: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_ContainsOpaqueTemplate() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(ContainsOpaqueTemplate)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ContainsOpaqueTemplate)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBlah) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContainsOpaqueTemplate), - "::", - stringify!(mBlah), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBaz) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(ContainsOpaqueTemplate), - "::", - stringify!(mBaz), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ContainsOpaqueTemplate", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of ContainsOpaqueTemplate", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: ContainsOpaqueTemplate::mBlah", + ][::std::mem::offset_of!(ContainsOpaqueTemplate, mBlah) - 0usize]; + [ + "Offset of field: ContainsOpaqueTemplate::mBaz", + ][::std::mem::offset_of!(ContainsOpaqueTemplate, mBaz) - 4usize]; +}; /// Should also derive Debug/Hash/PartialEq. #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] @@ -55,31 +35,18 @@ pub struct InheritsOpaqueTemplate { pub _base: u8, pub wow: *mut ::std::os::raw::c_char, } -#[test] -fn bindgen_test_layout_InheritsOpaqueTemplate() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(InheritsOpaqueTemplate)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(InheritsOpaqueTemplate)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).wow) as usize - ptr as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(InheritsOpaqueTemplate), - "::", - stringify!(wow), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of InheritsOpaqueTemplate", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of InheritsOpaqueTemplate", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: InheritsOpaqueTemplate::wow", + ][::std::mem::offset_of!(InheritsOpaqueTemplate, wow) - 8usize]; +}; impl Default for InheritsOpaqueTemplate { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/opaque-template-inst-member.rs b/bindgen-tests/tests/expectations/tests/opaque-template-inst-member.rs index 4f3f4b5724..4b070fa697 100644 --- a/bindgen-tests/tests/expectations/tests/opaque-template-inst-member.rs +++ b/bindgen-tests/tests/expectations/tests/opaque-template-inst-member.rs @@ -18,32 +18,22 @@ fn bindgen_test_layout_ContainsOpaqueTemplate() { assert_eq!( ::std::mem::size_of::(), 408usize, - concat!("Size of: ", stringify!(ContainsOpaqueTemplate)), + "Size of ContainsOpaqueTemplate", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(ContainsOpaqueTemplate)), + "Alignment of ContainsOpaqueTemplate", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mBlah) as usize - ptr as usize }, 0usize, - concat!( - "Offset of field: ", - stringify!(ContainsOpaqueTemplate), - "::", - stringify!(mBlah), - ), + "Offset of field: ContainsOpaqueTemplate::mBlah", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).mBaz) as usize - ptr as usize }, 404usize, - concat!( - "Offset of field: ", - stringify!(ContainsOpaqueTemplate), - "::", - stringify!(mBaz), - ), + "Offset of field: ContainsOpaqueTemplate::mBaz", ); } impl Default for ContainsOpaqueTemplate { @@ -74,22 +64,17 @@ fn bindgen_test_layout_InheritsOpaqueTemplate() { assert_eq!( ::std::mem::size_of::(), 416usize, - concat!("Size of: ", stringify!(InheritsOpaqueTemplate)), + "Size of InheritsOpaqueTemplate", ); assert_eq!( ::std::mem::align_of::(), 8usize, - concat!("Alignment of ", stringify!(InheritsOpaqueTemplate)), + "Alignment of InheritsOpaqueTemplate", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).wow) as usize - ptr as usize }, 408usize, - concat!( - "Offset of field: ", - stringify!(InheritsOpaqueTemplate), - "::", - stringify!(wow), - ), + "Offset of field: InheritsOpaqueTemplate::wow", ); } impl Default for InheritsOpaqueTemplate { diff --git a/bindgen-tests/tests/expectations/tests/opaque-template-instantiation-namespaced.rs b/bindgen-tests/tests/expectations/tests/opaque-template-instantiation-namespaced.rs index 57b20c78a9..58644e053d 100644 --- a/bindgen-tests/tests/expectations/tests/opaque-template-instantiation-namespaced.rs +++ b/bindgen-tests/tests/expectations/tests/opaque-template-instantiation-namespaced.rs @@ -9,8 +9,8 @@ pub mod root { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Template { - pub member: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member: T, } impl Default for Template { fn default() -> Self { @@ -26,83 +26,40 @@ pub mod root { pub struct Foo { pub c: ::std::os::raw::c_char, } - #[test] - fn bindgen_test_layout_Foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Foo), "::", stringify!(c)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; + ["Offset of field: Foo::c"][::std::mem::offset_of!(Foo, c) - 0usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct Bar { pub i: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).i) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(i)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Bar::i"][::std::mem::offset_of!(Bar, i) - 0usize]; + }; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct ContainsInstantiation { pub not_opaque: root::zoidberg::Template, } - #[test] - fn bindgen_test_layout_ContainsInstantiation() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ContainsInstantiation)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ContainsInstantiation)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).not_opaque) as usize - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContainsInstantiation), - "::", - stringify!(not_opaque), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of ContainsInstantiation", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of ContainsInstantiation", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ContainsInstantiation::not_opaque", + ][::std::mem::offset_of!(ContainsInstantiation, not_opaque) - 0usize]; + }; impl Default for ContainsInstantiation { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -117,49 +74,28 @@ pub mod root { pub struct ContainsOpaqueInstantiation { pub opaque: u32, } - #[test] - fn bindgen_test_layout_ContainsOpaqueInstantiation() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(ContainsOpaqueInstantiation)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ContainsOpaqueInstantiation)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).opaque) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContainsOpaqueInstantiation), - "::", - stringify!(opaque), - ), - ); - } - } - #[test] - fn __bindgen_test_layout_Template_open0_Foo_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 1usize, - concat!( - "Size of template specialization: ", - stringify!(root::zoidberg::Template < root::zoidberg::Foo >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 1usize, - concat!( - "Alignment of template specialization: ", - stringify!(root::zoidberg::Template < root::zoidberg::Foo >), - ), - ); + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of ContainsOpaqueInstantiation", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of ContainsOpaqueInstantiation", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: ContainsOpaqueInstantiation::opaque", + ][::std::mem::offset_of!(ContainsOpaqueInstantiation, opaque) - 0usize]; + }; } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of template specialization: Template_open0_Foo_close0", + ][::std::mem::size_of::>() + - 1usize]; + [ + "Align of template specialization: Template_open0_Foo_close0", + ][::std::mem::align_of::>() + - 1usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/opaque-template-instantiation.rs b/bindgen-tests/tests/expectations/tests/opaque-template-instantiation.rs index a1cdbcc977..ab68c21856 100644 --- a/bindgen-tests/tests/expectations/tests/opaque-template-instantiation.rs +++ b/bindgen-tests/tests/expectations/tests/opaque-template-instantiation.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Template { - pub member: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member: T, } impl Default for Template { fn default() -> Self { @@ -19,31 +19,18 @@ impl Default for Template { pub struct ContainsInstantiation { pub not_opaque: Template<::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_ContainsInstantiation() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(ContainsInstantiation)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ContainsInstantiation)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).not_opaque) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContainsInstantiation), - "::", - stringify!(not_opaque), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ContainsInstantiation", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of ContainsInstantiation", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ContainsInstantiation::not_opaque", + ][::std::mem::offset_of!(ContainsInstantiation, not_opaque) - 0usize]; +}; impl Default for ContainsInstantiation { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -58,47 +45,24 @@ impl Default for ContainsInstantiation { pub struct ContainsOpaqueInstantiation { pub opaque: u32, } -#[test] -fn bindgen_test_layout_ContainsOpaqueInstantiation() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(ContainsOpaqueInstantiation)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ContainsOpaqueInstantiation)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).opaque) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContainsOpaqueInstantiation), - "::", - stringify!(opaque), - ), - ); -} -#[test] -fn __bindgen_test_layout_Template_open0_char_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 1usize, - concat!( - "Size of template specialization: ", - stringify!(Template < ::std::os::raw::c_char >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 1usize, - concat!( - "Alignment of template specialization: ", - stringify!(Template < ::std::os::raw::c_char >), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ContainsOpaqueInstantiation", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of ContainsOpaqueInstantiation", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: ContainsOpaqueInstantiation::opaque", + ][::std::mem::offset_of!(ContainsOpaqueInstantiation, opaque) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Template_open0_char_close0", + ][::std::mem::size_of::>() - 1usize]; + [ + "Align of template specialization: Template_open0_char_close0", + ][::std::mem::align_of::>() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/opaque-tracing.rs b/bindgen-tests/tests/expectations/tests/opaque-tracing.rs index 3bc54c5ed8..60d249a88c 100644 --- a/bindgen-tests/tests/expectations/tests/opaque-tracing.rs +++ b/bindgen-tests/tests/expectations/tests/opaque-tracing.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z3fooP9Container"] pub fn foo(c: *mut Container); } @@ -9,16 +9,8 @@ extern "C" { pub struct Container { pub _bindgen_opaque_blob: [u32; 2usize], } -#[test] -fn bindgen_test_layout_Container() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Container)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Container)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Container"][::std::mem::size_of::() - 8usize]; + ["Alignment of Container"][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/opaque_in_struct.rs b/bindgen-tests/tests/expectations/tests/opaque_in_struct.rs index 5a267a194b..b651cd3354 100644 --- a/bindgen-tests/tests/expectations/tests/opaque_in_struct.rs +++ b/bindgen-tests/tests/expectations/tests/opaque_in_struct.rs @@ -6,41 +6,21 @@ pub struct opaque { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_opaque() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(opaque)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(opaque)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of opaque"][::std::mem::size_of::() - 4usize]; + ["Alignment of opaque"][::std::mem::align_of::() - 4usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct container { pub contained: opaque, } -#[test] -fn bindgen_test_layout_container() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(container)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(container)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).contained) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(container), "::", stringify!(contained)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of container"][::std::mem::size_of::() - 4usize]; + ["Alignment of container"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: container::contained", + ][::std::mem::offset_of!(container, contained) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/opaque_pointer.rs b/bindgen-tests/tests/expectations/tests/opaque_pointer.rs index 36a120536e..ec519d9c6b 100644 --- a/bindgen-tests/tests/expectations/tests/opaque_pointer.rs +++ b/bindgen-tests/tests/expectations/tests/opaque_pointer.rs @@ -6,19 +6,11 @@ pub struct OtherOpaque { pub _bindgen_opaque_blob: u32, } -#[test] -fn bindgen_test_layout_OtherOpaque() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(OtherOpaque)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(OtherOpaque)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of OtherOpaque"][::std::mem::size_of::() - 4usize]; + ["Alignment of OtherOpaque"][::std::mem::align_of::() - 4usize]; +}; ///
#[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] @@ -32,41 +24,20 @@ pub struct WithOpaquePtr { pub other: u32, pub t: OtherOpaque, } -#[test] -fn bindgen_test_layout_WithOpaquePtr() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(WithOpaquePtr)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(WithOpaquePtr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).whatever) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithOpaquePtr), - "::", - stringify!(whatever), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).other) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(WithOpaquePtr), "::", stringify!(other)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).t) as usize - ptr as usize }, - 12usize, - concat!("Offset of field: ", stringify!(WithOpaquePtr), "::", stringify!(t)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithOpaquePtr"][::std::mem::size_of::() - 16usize]; + ["Alignment of WithOpaquePtr"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: WithOpaquePtr::whatever", + ][::std::mem::offset_of!(WithOpaquePtr, whatever) - 0usize]; + [ + "Offset of field: WithOpaquePtr::other", + ][::std::mem::offset_of!(WithOpaquePtr, other) - 8usize]; + [ + "Offset of field: WithOpaquePtr::t", + ][::std::mem::offset_of!(WithOpaquePtr, t) - 12usize]; +}; impl Default for WithOpaquePtr { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/opencl_vector.rs b/bindgen-tests/tests/expectations/tests/opencl_vector.rs new file mode 100644 index 0000000000..3c2525c845 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/opencl_vector.rs @@ -0,0 +1,6 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub type float4 = [f32; 4usize]; +pub type float2 = [f32; 2usize]; +unsafe extern "C" { + pub fn foo(a: float2, b: float2) -> float4; +} diff --git a/bindgen-tests/tests/expectations/tests/operator.rs b/bindgen-tests/tests/expectations/tests/operator.rs index fa018724fc..ce5a652d8d 100644 --- a/bindgen-tests/tests/expectations/tests/operator.rs +++ b/bindgen-tests/tests/expectations/tests/operator.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z20operator_informationv"] pub fn operator_information() -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/operator_equals.rs b/bindgen-tests/tests/expectations/tests/operator_equals.rs new file mode 100644 index 0000000000..ff9f4fdd22 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/operator_equals.rs @@ -0,0 +1,24 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone)] +pub struct SomeClass { + pub _address: u8, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of SomeClass"][::std::mem::size_of::() - 1usize]; + ["Alignment of SomeClass"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { + #[link_name = "\u{1}_ZN9SomeClassaSERKS_"] + pub fn SomeClass_operatorequals( + this: *mut SomeClass, + another: *const SomeClass, + ) -> bool; +} +impl SomeClass { + #[inline] + pub unsafe fn operatorequals(&mut self, another: *const SomeClass) -> bool { + SomeClass_operatorequals(self, another) + } +} diff --git a/bindgen-tests/tests/expectations/tests/overloading.rs b/bindgen-tests/tests/expectations/tests/overloading.rs index 3e8fced8e7..96504b38eb 100644 --- a/bindgen-tests/tests/expectations/tests/overloading.rs +++ b/bindgen-tests/tests/expectations/tests/overloading.rs @@ -1,17 +1,17 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z8Evaluatec"] pub fn Evaluate(r: ::std::os::raw::c_char) -> bool; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z8Evaluateii"] pub fn Evaluate1(x: ::std::os::raw::c_int, y: ::std::os::raw::c_int) -> bool; } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3foo10MyFunctionEv"] pub fn foo_MyFunction(); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3bar10MyFunctionEv"] pub fn bar_MyFunction(); } diff --git a/bindgen-tests/tests/expectations/tests/packed-bitfield.rs b/bindgen-tests/tests/expectations/tests/packed-bitfield.rs index 8d4b87453f..4e3918f558 100644 --- a/bindgen-tests/tests/expectations/tests/packed-bitfield.rs +++ b/bindgen-tests/tests/expectations/tests/packed-bitfield.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C, packed)] #[derive(Debug, Default, Copy, Clone)] @@ -89,19 +151,11 @@ pub struct Date { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, } -#[test] -fn bindgen_test_layout_Date() { - assert_eq!( - ::std::mem::size_of::(), - 3usize, - concat!("Size of: ", stringify!(Date)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Date)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Date"][::std::mem::size_of::() - 3usize]; + ["Alignment of Date"][::std::mem::align_of::() - 1usize]; +}; impl Date { #[inline] pub fn day(&self) -> ::std::os::raw::c_uchar { @@ -115,6 +169,30 @@ impl Date { } } #[inline] + pub unsafe fn day_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 5u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_day_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 5u8, + val as u64, + ) + } + } + #[inline] pub fn month(&self) -> ::std::os::raw::c_uchar { unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 4u8) as u8) } } @@ -126,6 +204,30 @@ impl Date { } } #[inline] + pub unsafe fn month_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 5usize, 4u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_month_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn year(&self) -> ::std::os::raw::c_short { unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 15u8) as u16) } } @@ -137,6 +239,31 @@ impl Date { } } #[inline] + pub unsafe fn year_raw(this: *const Self) -> ::std::os::raw::c_short { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 9usize, 15u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_year_raw(this: *mut Self, val: ::std::os::raw::c_short) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 3usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 15u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( day: ::std::os::raw::c_uchar, month: ::std::os::raw::c_uchar, diff --git a/bindgen-tests/tests/expectations/tests/packed-n-with-padding.rs b/bindgen-tests/tests/expectations/tests/packed-n-with-padding.rs index 3a24767eeb..162a1bebed 100644 --- a/bindgen-tests/tests/expectations/tests/packed-n-with-padding.rs +++ b/bindgen-tests/tests/expectations/tests/packed-n-with-padding.rs @@ -7,38 +7,12 @@ pub struct Packed { pub c: ::std::os::raw::c_char, pub d: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Packed() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 10usize, - concat!("Size of: ", stringify!(Packed)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(Packed)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Packed), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 2usize, - concat!("Offset of field: ", stringify!(Packed), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Packed), "::", stringify!(c)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 6usize, - concat!("Offset of field: ", stringify!(Packed), "::", stringify!(d)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Packed"][::std::mem::size_of::() - 10usize]; + ["Alignment of Packed"][::std::mem::align_of::() - 2usize]; + ["Offset of field: Packed::a"][::std::mem::offset_of!(Packed, a) - 0usize]; + ["Offset of field: Packed::b"][::std::mem::offset_of!(Packed, b) - 2usize]; + ["Offset of field: Packed::c"][::std::mem::offset_of!(Packed, c) - 4usize]; + ["Offset of field: Packed::d"][::std::mem::offset_of!(Packed, d) - 6usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/packed-vtable.rs b/bindgen-tests/tests/expectations/tests/packed-vtable.rs index b85143250f..362017a233 100644 --- a/bindgen-tests/tests/expectations/tests/packed-vtable.rs +++ b/bindgen-tests/tests/expectations/tests/packed-vtable.rs @@ -8,15 +8,11 @@ pub struct PackedVtable { } #[test] fn bindgen_test_layout_PackedVtable() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(PackedVtable)), - ); + assert_eq!(::std::mem::size_of::(), 8usize, "Size of PackedVtable"); assert_eq!( ::std::mem::align_of::(), 1usize, - concat!("Alignment of ", stringify!(PackedVtable)), + "Alignment of PackedVtable", ); } impl Default for PackedVtable { diff --git a/bindgen-tests/tests/expectations/tests/parm-union.rs b/bindgen-tests/tests/expectations/tests/parm-union.rs index 92a3c19576..6dee4ec7d5 100644 --- a/bindgen-tests/tests/expectations/tests/parm-union.rs +++ b/bindgen-tests/tests/expectations/tests/parm-union.rs @@ -4,20 +4,12 @@ pub struct Struct { pub _address: u8, } -#[test] -fn bindgen_test_layout_Struct() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Struct)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Struct"][::std::mem::size_of::() - 1usize]; + ["Alignment of Struct"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN6Struct8FunctionER5Union"] pub fn Struct_Function(this: *mut Struct, arg1: *mut Union); } diff --git a/bindgen-tests/tests/expectations/tests/partial-specialization-and-inheritance.rs b/bindgen-tests/tests/expectations/tests/partial-specialization-and-inheritance.rs index 3ba3a82aa3..a4234d2aaa 100644 --- a/bindgen-tests/tests/expectations/tests/partial-specialization-and-inheritance.rs +++ b/bindgen-tests/tests/expectations/tests/partial-specialization-and-inheritance.rs @@ -1,4 +1,14 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +/// If Bindgen could only determine the size and alignment of a +/// type, it is represented like this. +#[derive(PartialEq, Copy, Clone, Debug, Hash)] +#[repr(C)] +pub struct __BindgenOpaqueArray(pub [T; N]); +impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } +} #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Base { @@ -14,20 +24,12 @@ pub struct Derived { pub struct Usage { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN5Usage13static_memberE"] - pub static mut Usage_static_member: [u32; 2usize]; -} -#[test] -fn bindgen_test_layout_Usage() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Usage)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Usage)), - ); + pub static mut Usage_static_member: __BindgenOpaqueArray; } +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Usage"][::std::mem::size_of::() - 1usize]; + ["Alignment of Usage"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/pointer-attr.rs b/bindgen-tests/tests/expectations/tests/pointer-attr.rs index edb29dc499..4d7e250b9c 100644 --- a/bindgen-tests/tests/expectations/tests/pointer-attr.rs +++ b/bindgen-tests/tests/expectations/tests/pointer-attr.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn a(arg1: *const ::std::os::raw::c_char); } diff --git a/bindgen-tests/tests/expectations/tests/prefix-link-name-c.rs b/bindgen-tests/tests/expectations/tests/prefix-link-name-c.rs index e81a3b667d..cb1ebfa4f7 100644 --- a/bindgen-tests/tests/expectations/tests/prefix-link-name-c.rs +++ b/bindgen-tests/tests/expectations/tests/prefix-link-name-c.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}foo_bar"] pub fn bar() -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/prefix-link-name-cpp.rs b/bindgen-tests/tests/expectations/tests/prefix-link-name-cpp.rs index bf53473d88..07cacc5f7a 100644 --- a/bindgen-tests/tests/expectations/tests/prefix-link-name-cpp.rs +++ b/bindgen-tests/tests/expectations/tests/prefix-link-name-cpp.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}foo_foo"] pub fn baz_foo() -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/private.rs b/bindgen-tests/tests/expectations/tests/private.rs index 2d37e95e35..bf1e853e6a 100644 --- a/bindgen-tests/tests/expectations/tests/private.rs +++ b/bindgen-tests/tests/expectations/tests/private.rs @@ -6,41 +6,17 @@ pub struct HasPrivate { ///
mIsPrivate: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_HasPrivate() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(HasPrivate)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(HasPrivate)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mNotPrivate) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(HasPrivate), - "::", - stringify!(mNotPrivate), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mIsPrivate) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(HasPrivate), - "::", - stringify!(mIsPrivate), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of HasPrivate"][::std::mem::size_of::() - 8usize]; + ["Alignment of HasPrivate"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: HasPrivate::mNotPrivate", + ][::std::mem::offset_of!(HasPrivate, mNotPrivate) - 0usize]; + [ + "Offset of field: HasPrivate::mIsPrivate", + ][::std::mem::offset_of!(HasPrivate, mIsPrivate) - 4usize]; +}; ///
#[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -48,41 +24,17 @@ pub struct VeryPrivate { mIsPrivate: ::std::os::raw::c_int, mIsAlsoPrivate: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_VeryPrivate() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(VeryPrivate)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(VeryPrivate)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mIsPrivate) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(VeryPrivate), - "::", - stringify!(mIsPrivate), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mIsAlsoPrivate) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(VeryPrivate), - "::", - stringify!(mIsAlsoPrivate), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of VeryPrivate"][::std::mem::size_of::() - 8usize]; + ["Alignment of VeryPrivate"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: VeryPrivate::mIsPrivate", + ][::std::mem::offset_of!(VeryPrivate, mIsPrivate) - 0usize]; + [ + "Offset of field: VeryPrivate::mIsAlsoPrivate", + ][::std::mem::offset_of!(VeryPrivate, mIsAlsoPrivate) - 4usize]; +}; ///
#[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -91,38 +43,16 @@ pub struct ContradictPrivate { pub mNotPrivate: ::std::os::raw::c_int, mIsPrivate: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_ContradictPrivate() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(ContradictPrivate)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(ContradictPrivate)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mNotPrivate) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContradictPrivate), - "::", - stringify!(mNotPrivate), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mIsPrivate) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(ContradictPrivate), - "::", - stringify!(mIsPrivate), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ContradictPrivate"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of ContradictPrivate", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: ContradictPrivate::mNotPrivate", + ][::std::mem::offset_of!(ContradictPrivate, mNotPrivate) - 0usize]; + [ + "Offset of field: ContradictPrivate::mIsPrivate", + ][::std::mem::offset_of!(ContradictPrivate, mIsPrivate) - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/private_fields.rs b/bindgen-tests/tests/expectations/tests/private_fields.rs index cc54f2856f..a5d9e84499 100644 --- a/bindgen-tests/tests/expectations/tests/private_fields.rs +++ b/bindgen-tests/tests/expectations/tests/private_fields.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -89,31 +151,13 @@ pub struct PubPriv { pub x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_PubPriv() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(PubPriv)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(PubPriv)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(PubPriv), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(PubPriv), "::", stringify!(y)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of PubPriv"][::std::mem::size_of::() - 8usize]; + ["Alignment of PubPriv"][::std::mem::align_of::() - 4usize]; + ["Offset of field: PubPriv::x"][::std::mem::offset_of!(PubPriv, x) - 0usize]; + ["Offset of field: PubPriv::y"][::std::mem::offset_of!(PubPriv, y) - 4usize]; +}; #[repr(C)] #[repr(align(4))] #[derive(Debug, Default, Copy, Clone)] @@ -122,19 +166,13 @@ pub struct PrivateBitFields { _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub __bindgen_padding_0: [u8; 3usize], } -#[test] -fn bindgen_test_layout_PrivateBitFields() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(PrivateBitFields)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(PrivateBitFields)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of PrivateBitFields"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of PrivateBitFields", + ][::std::mem::align_of::() - 4usize]; +}; impl PrivateBitFields { #[inline] fn a(&self) -> ::std::os::raw::c_uint { @@ -148,6 +186,31 @@ impl PrivateBitFields { } } #[inline] + unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 4u8) + as u32, + ) + } + } + #[inline] + unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 4u8, + val as u64, + ) + } + } + #[inline] fn b(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u32) } } @@ -159,6 +222,31 @@ impl PrivateBitFields { } } #[inline] + unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 4usize, 4u8) + as u32, + ) + } + } + #[inline] + unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 4u8, + val as u64, + ) + } + } + #[inline] fn new_bitfield_1( a: ::std::os::raw::c_uint, b: ::std::os::raw::c_uint, @@ -193,19 +281,11 @@ pub struct PublicBitFields { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub __bindgen_padding_0: [u8; 3usize], } -#[test] -fn bindgen_test_layout_PublicBitFields() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(PublicBitFields)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(PublicBitFields)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of PublicBitFields"][::std::mem::size_of::() - 4usize]; + ["Alignment of PublicBitFields"][::std::mem::align_of::() - 4usize]; +}; impl PublicBitFields { #[inline] pub fn a(&self) -> ::std::os::raw::c_uint { @@ -219,6 +299,31 @@ impl PublicBitFields { } } #[inline] + pub unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn b(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u32) } } @@ -230,6 +335,31 @@ impl PublicBitFields { } } #[inline] + pub unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 4usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( a: ::std::os::raw::c_uint, b: ::std::os::raw::c_uint, @@ -264,19 +394,11 @@ pub struct MixedBitFields { _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub __bindgen_padding_0: [u8; 3usize], } -#[test] -fn bindgen_test_layout_MixedBitFields() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(MixedBitFields)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(MixedBitFields)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of MixedBitFields"][::std::mem::size_of::() - 4usize]; + ["Alignment of MixedBitFields"][::std::mem::align_of::() - 4usize]; +}; impl MixedBitFields { #[inline] fn a(&self) -> ::std::os::raw::c_uint { @@ -290,6 +412,31 @@ impl MixedBitFields { } } #[inline] + unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 4u8) + as u32, + ) + } + } + #[inline] + unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 4u8, + val as u64, + ) + } + } + #[inline] pub fn d(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u32) } } @@ -301,6 +448,31 @@ impl MixedBitFields { } } #[inline] + pub unsafe fn d_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 4usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_d_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 4u8, + val as u64, + ) + } + } + #[inline] fn new_bitfield_1( a: ::std::os::raw::c_uint, d: ::std::os::raw::c_uint, @@ -332,62 +504,36 @@ impl MixedBitFields { pub struct Base { pub member: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Base() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Base)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Base)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Base), "::", stringify!(member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Base"][::std::mem::size_of::() - 4usize]; + ["Alignment of Base"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Base::member"][::std::mem::offset_of!(Base, member) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct InheritsPrivately { _base: Base, } -#[test] -fn bindgen_test_layout_InheritsPrivately() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(InheritsPrivately)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(InheritsPrivately)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of InheritsPrivately"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of InheritsPrivately", + ][::std::mem::align_of::() - 4usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct InheritsPublically { pub _base: Base, } -#[test] -fn bindgen_test_layout_InheritsPublically() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(InheritsPublically)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(InheritsPublically)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of InheritsPublically"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of InheritsPublically", + ][::std::mem::align_of::() - 4usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct WithAnonStruct { @@ -399,74 +545,40 @@ pub struct WithAnonStruct { pub struct WithAnonStruct__bindgen_ty_1 { pub a: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_WithAnonStruct__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithAnonStruct__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithAnonStruct__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithAnonStruct__bindgen_ty_1), - "::", - stringify!(a), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of WithAnonStruct__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of WithAnonStruct__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WithAnonStruct__bindgen_ty_1::a", + ][::std::mem::offset_of!(WithAnonStruct__bindgen_ty_1, a) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct WithAnonStruct__bindgen_ty_2 { pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_WithAnonStruct__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithAnonStruct__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithAnonStruct__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithAnonStruct__bindgen_ty_2), - "::", - stringify!(b), - ), - ); -} -#[test] -fn bindgen_test_layout_WithAnonStruct() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(WithAnonStruct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithAnonStruct)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of WithAnonStruct__bindgen_ty_2", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of WithAnonStruct__bindgen_ty_2", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WithAnonStruct__bindgen_ty_2::b", + ][::std::mem::offset_of!(WithAnonStruct__bindgen_ty_2, b) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithAnonStruct"][::std::mem::size_of::() - 8usize]; + ["Alignment of WithAnonStruct"][::std::mem::align_of::() - 4usize]; +}; #[repr(C)] #[derive(Copy, Clone)] pub struct WithAnonUnion { @@ -477,19 +589,15 @@ pub struct WithAnonUnion { pub union WithAnonUnion__bindgen_ty_1 { pub _address: u8, } -#[test] -fn bindgen_test_layout_WithAnonUnion__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(WithAnonUnion__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(WithAnonUnion__bindgen_ty_1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of WithAnonUnion__bindgen_ty_1", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of WithAnonUnion__bindgen_ty_1", + ][::std::mem::align_of::() - 1usize]; +}; impl Default for WithAnonUnion__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -499,19 +607,11 @@ impl Default for WithAnonUnion__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_WithAnonUnion() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(WithAnonUnion)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(WithAnonUnion)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithAnonUnion"][::std::mem::size_of::() - 1usize]; + ["Alignment of WithAnonUnion"][::std::mem::align_of::() - 1usize]; +}; impl Default for WithAnonUnion { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -532,36 +632,16 @@ pub struct Override { _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, pub __bindgen_padding_0: u16, } -#[test] -fn bindgen_test_layout_Override() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Override)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Override)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Override), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Override), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).private_c) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Override), "::", stringify!(private_c)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Override"][::std::mem::size_of::() - 16usize]; + ["Alignment of Override"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Override::a"][::std::mem::offset_of!(Override, a) - 0usize]; + ["Offset of field: Override::b"][::std::mem::offset_of!(Override, b) - 4usize]; + [ + "Offset of field: Override::private_c", + ][::std::mem::offset_of!(Override, private_c) - 8usize]; +}; impl Override { #[inline] pub fn bf_a(&self) -> ::std::os::raw::c_uint { @@ -575,6 +655,31 @@ impl Override { } } #[inline] + pub unsafe fn bf_a_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 4u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bf_a_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 4u8, + val as u64, + ) + } + } + #[inline] fn bf_b(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u32) } } @@ -586,6 +691,31 @@ impl Override { } } #[inline] + unsafe fn bf_b_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 4usize, 4u8) + as u32, + ) + } + } + #[inline] + unsafe fn set_bf_b_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 4u8, + val as u64, + ) + } + } + #[inline] fn private_bf_c(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 4u8) as u32) } } @@ -597,6 +727,31 @@ impl Override { } } #[inline] + unsafe fn private_bf_c_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 8usize, 4u8) + as u32, + ) + } + } + #[inline] + unsafe fn set_private_bf_c_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 4u8, + val as u64, + ) + } + } + #[inline] fn new_bitfield_1( bf_a: ::std::os::raw::c_uint, bf_b: ::std::os::raw::c_uint, diff --git a/bindgen-tests/tests/expectations/tests/ptr32-has-different-size.rs b/bindgen-tests/tests/expectations/tests/ptr32-has-different-size.rs index bdcc170af7..f4f3ab4294 100644 --- a/bindgen-tests/tests/expectations/tests/ptr32-has-different-size.rs +++ b/bindgen-tests/tests/expectations/tests/ptr32-has-different-size.rs @@ -4,31 +4,14 @@ pub struct TEST_STRUCT { pub ptr_32bit: u32, } -#[test] -fn bindgen_test_layout_TEST_STRUCT() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(TEST_STRUCT)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(TEST_STRUCT)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ptr_32bit) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(TEST_STRUCT), - "::", - stringify!(ptr_32bit), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of TEST_STRUCT"][::std::mem::size_of::() - 4usize]; + ["Alignment of TEST_STRUCT"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: TEST_STRUCT::ptr_32bit", + ][::std::mem::offset_of!(TEST_STRUCT, ptr_32bit) - 0usize]; +}; impl Default for TEST_STRUCT { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/public-dtor.rs b/bindgen-tests/tests/expectations/tests/public-dtor.rs index ad0ae6d919..578d3e76a5 100644 --- a/bindgen-tests/tests/expectations/tests/public-dtor.rs +++ b/bindgen-tests/tests/expectations/tests/public-dtor.rs @@ -4,20 +4,12 @@ pub struct cv_Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_cv_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(cv_Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(cv_Foo)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of cv_Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of cv_Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN2cv3FooD1Ev"] pub fn cv_Foo_Foo_destructor(this: *mut cv_Foo); } @@ -32,16 +24,8 @@ impl cv_Foo { pub struct cv_Bar { pub _address: u8, } -#[test] -fn bindgen_test_layout_cv_Bar() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(cv_Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(cv_Bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of cv_Bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of cv_Bar"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/redeclaration.rs b/bindgen-tests/tests/expectations/tests/redeclaration.rs index 05b7aecd3e..736d379f01 100644 --- a/bindgen-tests/tests/expectations/tests/redeclaration.rs +++ b/bindgen-tests/tests/expectations/tests/redeclaration.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo(); } diff --git a/bindgen-tests/tests/expectations/tests/redundant-packed-and-align.rs b/bindgen-tests/tests/expectations/tests/redundant-packed-and-align.rs index b5feaa140a..c01762ca98 100644 --- a/bindgen-tests/tests/expectations/tests/redundant-packed-and-align.rs +++ b/bindgen-tests/tests/expectations/tests/redundant-packed-and-align.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[repr(align(8))] @@ -90,31 +152,19 @@ pub struct redundant_packed { pub a: u32, pub b: u32, } -#[test] -fn bindgen_test_layout_redundant_packed() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(redundant_packed)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(redundant_packed)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(redundant_packed), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(redundant_packed), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of redundant_packed"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of redundant_packed", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: redundant_packed::a", + ][::std::mem::offset_of!(redundant_packed, a) - 0usize]; + [ + "Offset of field: redundant_packed::b", + ][::std::mem::offset_of!(redundant_packed, b) - 4usize]; +}; #[repr(C)] #[repr(align(8))] #[derive(Debug, Default, Copy, Clone)] @@ -124,41 +174,21 @@ pub struct redundant_packed_bitfield { pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub c: u32, } -#[test] -fn bindgen_test_layout_redundant_packed_bitfield() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(redundant_packed_bitfield)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(redundant_packed_bitfield)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(redundant_packed_bitfield), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(redundant_packed_bitfield), - "::", - stringify!(c), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of redundant_packed_bitfield", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of redundant_packed_bitfield", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: redundant_packed_bitfield::a", + ][::std::mem::offset_of!(redundant_packed_bitfield, a) - 0usize]; + [ + "Offset of field: redundant_packed_bitfield::c", + ][::std::mem::offset_of!(redundant_packed_bitfield, c) - 4usize]; +}; impl redundant_packed_bitfield { #[inline] pub fn b0(&self) -> u8 { @@ -172,6 +202,30 @@ impl redundant_packed_bitfield { } } #[inline] + pub unsafe fn b0_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_b0_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b1(&self) -> u8 { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u8) } } @@ -183,6 +237,30 @@ impl redundant_packed_bitfield { } } #[inline] + pub unsafe fn b1_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_b1_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1(b0: u8, b1: u8) -> __BindgenBitfieldUnit<[u8; 1usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); __bindgen_bitfield_unit @@ -213,41 +291,21 @@ pub union redundant_packed_union { pub a: u64, pub b: u32, } -#[test] -fn bindgen_test_layout_redundant_packed_union() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(redundant_packed_union)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(redundant_packed_union)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(redundant_packed_union), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(redundant_packed_union), - "::", - stringify!(b), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of redundant_packed_union", + ][::std::mem::size_of::() - 16usize]; + [ + "Alignment of redundant_packed_union", + ][::std::mem::align_of::() - 16usize]; + [ + "Offset of field: redundant_packed_union::a", + ][::std::mem::offset_of!(redundant_packed_union, a) - 0usize]; + [ + "Offset of field: redundant_packed_union::b", + ][::std::mem::offset_of!(redundant_packed_union, b) - 0usize]; +}; impl Default for redundant_packed_union { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -263,26 +321,12 @@ impl Default for redundant_packed_union { pub struct inner { pub a: u8, } -#[test] -fn bindgen_test_layout_inner() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(inner)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(inner)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(inner), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of inner"][::std::mem::size_of::() - 2usize]; + ["Alignment of inner"][::std::mem::align_of::() - 2usize]; + ["Offset of field: inner::a"][::std::mem::offset_of!(inner, a) - 0usize]; +}; #[repr(C)] #[repr(align(8))] #[derive(Debug, Default, Copy, Clone)] @@ -290,41 +334,21 @@ pub struct outer_redundant_packed { pub a: [inner; 2usize], pub b: u32, } -#[test] -fn bindgen_test_layout_outer_redundant_packed() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(outer_redundant_packed)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(outer_redundant_packed)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(outer_redundant_packed), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(outer_redundant_packed), - "::", - stringify!(b), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of outer_redundant_packed", + ][::std::mem::size_of::() - 8usize]; + [ + "Alignment of outer_redundant_packed", + ][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: outer_redundant_packed::a", + ][::std::mem::offset_of!(outer_redundant_packed, a) - 0usize]; + [ + "Offset of field: outer_redundant_packed::b", + ][::std::mem::offset_of!(outer_redundant_packed, b) - 4usize]; +}; #[repr(C)] #[repr(align(4))] #[derive(Debug, Default, Copy, Clone)] @@ -332,38 +356,18 @@ pub struct redundant_pragma_packed { pub a: u8, pub b: u16, } -#[test] -fn bindgen_test_layout_redundant_pragma_packed() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(redundant_pragma_packed)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(redundant_pragma_packed)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(redundant_pragma_packed), - "::", - stringify!(a), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(redundant_pragma_packed), - "::", - stringify!(b), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of redundant_pragma_packed", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of redundant_pragma_packed", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: redundant_pragma_packed::a", + ][::std::mem::offset_of!(redundant_pragma_packed, a) - 0usize]; + [ + "Offset of field: redundant_pragma_packed::b", + ][::std::mem::offset_of!(redundant_pragma_packed, b) - 2usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/ref_argument_array.rs b/bindgen-tests/tests/expectations/tests/ref_argument_array.rs index 0ca31312fe..4928a185fe 100644 --- a/bindgen-tests/tests/expectations/tests/ref_argument_array.rs +++ b/bindgen-tests/tests/expectations/tests/ref_argument_array.rs @@ -12,19 +12,11 @@ pub struct nsID__bindgen_vtable { pub struct nsID { pub vtable_: *const nsID__bindgen_vtable, } -#[test] -fn bindgen_test_layout_nsID() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsID)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsID)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of nsID"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsID"][::std::mem::align_of::() - 8usize]; +}; impl Default for nsID { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -34,7 +26,7 @@ impl Default for nsID { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN4nsID16ToProvidedStringERA10_c"] pub fn nsID_ToProvidedString( this: *mut ::std::os::raw::c_void, diff --git a/bindgen-tests/tests/expectations/tests/reparented_replacement.rs b/bindgen-tests/tests/expectations/tests/reparented_replacement.rs index f2f70482eb..9b2cc33ce9 100644 --- a/bindgen-tests/tests/expectations/tests/reparented_replacement.rs +++ b/bindgen-tests/tests/expectations/tests/reparented_replacement.rs @@ -12,26 +12,12 @@ pub mod root { pub struct Bar { pub bazz: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bazz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(bazz)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Bar::bazz"][::std::mem::offset_of!(Bar, bazz) - 0usize]; + }; } pub type ReferencesBar = root::foo::Bar; } diff --git a/bindgen-tests/tests/expectations/tests/replace_template_alias.rs b/bindgen-tests/tests/expectations/tests/replace_template_alias.rs index 6d656b2be6..2efa164ddf 100644 --- a/bindgen-tests/tests/expectations/tests/replace_template_alias.rs +++ b/bindgen-tests/tests/expectations/tests/replace_template_alias.rs @@ -6,8 +6,8 @@ pub type JS_detail_MaybeWrapped = T; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct JS_Rooted { - pub ptr: JS_detail_MaybeWrapped, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub ptr: JS_detail_MaybeWrapped, } impl Default for JS_Rooted { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/replace_use.rs b/bindgen-tests/tests/expectations/tests/replace_use.rs index b21fd03cac..ebf9657176 100644 --- a/bindgen-tests/tests/expectations/tests/replace_use.rs +++ b/bindgen-tests/tests/expectations/tests/replace_use.rs @@ -10,36 +10,18 @@ pub struct nsTArray { pub struct Test { pub a: nsTArray, } -#[test] -fn bindgen_test_layout_Test() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Test)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Test)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(a)), - ); -} -#[test] -fn __bindgen_test_layout_nsTArray_open0_long_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of template specialization: ", stringify!(nsTArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of template specialization: ", stringify!(nsTArray)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 4usize]; + ["Alignment of Test"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Test::a"][::std::mem::offset_of!(Test, a) - 0usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: nsTArray_open0_long_close0", + ][::std::mem::size_of::() - 4usize]; + [ + "Align of template specialization: nsTArray_open0_long_close0", + ][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/replaces_double.rs b/bindgen-tests/tests/expectations/tests/replaces_double.rs index 30966355fe..e764113f21 100644 --- a/bindgen-tests/tests/expectations/tests/replaces_double.rs +++ b/bindgen-tests/tests/expectations/tests/replaces_double.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Wrapper_Wrapped { - pub t: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, } impl Default for Wrapper_Wrapped { fn default() -> Self { @@ -18,8 +18,8 @@ pub type Wrapper_Type = Wrapper_Wrapped; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Rooted { - pub ptr: Rooted_MaybeWrapped, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub ptr: Rooted_MaybeWrapped, } ///
pub type Rooted_MaybeWrapped = T; diff --git a/bindgen-tests/tests/expectations/tests/repr-align.rs b/bindgen-tests/tests/expectations/tests/repr-align.rs index b8a7f1e6ea..6afc0ba859 100644 --- a/bindgen-tests/tests/expectations/tests/repr-align.rs +++ b/bindgen-tests/tests/expectations/tests/repr-align.rs @@ -11,21 +11,17 @@ pub struct a { fn bindgen_test_layout_a() { const UNINIT: ::std::mem::MaybeUninit
= ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 8usize, concat!("Size of: ", stringify!(a))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(a)), - ); + assert_eq!(::std::mem::size_of::(), 8usize, "Size of a"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of a"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(a), "::", stringify!(b)), + "Offset of field: a::b", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(a), "::", stringify!(c)), + "Offset of field: a::c", ); } #[repr(C)] @@ -39,20 +35,16 @@ pub struct b { fn bindgen_test_layout_b() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 8usize, concat!("Size of: ", stringify!(b))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(b)), - ); + assert_eq!(::std::mem::size_of::(), 8usize, "Size of b"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of b"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(b), "::", stringify!(b)), + "Offset of field: b::b", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, 4usize, - concat!("Offset of field: ", stringify!(b), "::", stringify!(c)), + "Offset of field: b::c", ); } diff --git a/bindgen-tests/tests/expectations/tests/resolved_type_def_function.rs b/bindgen-tests/tests/expectations/tests/resolved_type_def_function.rs index 8fe7eb7da2..cfbab6b968 100644 --- a/bindgen-tests/tests/expectations/tests/resolved_type_def_function.rs +++ b/bindgen-tests/tests/expectations/tests/resolved_type_def_function.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] pub type FuncType = ::std::option::Option; -extern "C" { +unsafe extern "C" { pub fn Func(); } diff --git a/bindgen-tests/tests/expectations/tests/same_struct_name_in_different_namespaces.rs b/bindgen-tests/tests/expectations/tests/same_struct_name_in_different_namespaces.rs index cbdea272aa..e6e4088abf 100644 --- a/bindgen-tests/tests/expectations/tests/same_struct_name_in_different_namespaces.rs +++ b/bindgen-tests/tests/expectations/tests/same_struct_name_in_different_namespaces.rs @@ -10,28 +10,14 @@ pub struct JS_shadow_Zone { pub x: ::std::os::raw::c_int, pub y: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_JS_shadow_Zone() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(JS_shadow_Zone)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(JS_shadow_Zone)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(JS_shadow_Zone), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(JS_shadow_Zone), "::", stringify!(y)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of JS_shadow_Zone"][::std::mem::size_of::() - 8usize]; + ["Alignment of JS_shadow_Zone"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: JS_shadow_Zone::x", + ][::std::mem::offset_of!(JS_shadow_Zone, x) - 0usize]; + [ + "Offset of field: JS_shadow_Zone::y", + ][::std::mem::offset_of!(JS_shadow_Zone, y) - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/sentry-defined-multiple-times.rs b/bindgen-tests/tests/expectations/tests/sentry-defined-multiple-times.rs index b881d72dfd..0fe153e700 100644 --- a/bindgen-tests/tests/expectations/tests/sentry-defined-multiple-times.rs +++ b/bindgen-tests/tests/expectations/tests/sentry-defined-multiple-times.rs @@ -21,85 +21,47 @@ pub mod root { pub struct sentry { pub i_am_plain_sentry: bool, } - #[test] - fn bindgen_test_layout_sentry() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(sentry)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(sentry)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).i_am_plain_sentry) as usize - - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(sentry), - "::", - stringify!(i_am_plain_sentry), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of sentry"][::std::mem::size_of::() - 1usize]; + ["Alignment of sentry"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: sentry::i_am_plain_sentry", + ][::std::mem::offset_of!(sentry, i_am_plain_sentry) - 0usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct NotTemplateWrapper { pub _address: u8, } - #[test] - fn bindgen_test_layout_NotTemplateWrapper() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(NotTemplateWrapper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(NotTemplateWrapper)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of NotTemplateWrapper", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of NotTemplateWrapper", + ][::std::mem::align_of::() - 1usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct NotTemplateWrapper_sentry { pub i_am_not_template_wrapper_sentry: ::std::os::raw::c_char, } - #[test] - fn bindgen_test_layout_NotTemplateWrapper_sentry() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(NotTemplateWrapper_sentry)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(NotTemplateWrapper_sentry)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).i_am_not_template_wrapper_sentry) - as usize - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(NotTemplateWrapper_sentry), - "::", - stringify!(i_am_not_template_wrapper_sentry), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of NotTemplateWrapper_sentry", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of NotTemplateWrapper_sentry", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: NotTemplateWrapper_sentry::i_am_not_template_wrapper_sentry", + ][::std::mem::offset_of!( + NotTemplateWrapper_sentry, i_am_not_template_wrapper_sentry + ) - 0usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct InlineNotTemplateWrapper { @@ -110,47 +72,29 @@ pub mod root { pub struct InlineNotTemplateWrapper_sentry { pub i_am_inline_not_template_wrapper_sentry: bool, } - #[test] - fn bindgen_test_layout_InlineNotTemplateWrapper_sentry() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(InlineNotTemplateWrapper_sentry)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(InlineNotTemplateWrapper_sentry)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).i_am_inline_not_template_wrapper_sentry) - as usize - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(InlineNotTemplateWrapper_sentry), - "::", - stringify!(i_am_inline_not_template_wrapper_sentry), - ), - ); - } - #[test] - fn bindgen_test_layout_InlineNotTemplateWrapper() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(InlineNotTemplateWrapper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(InlineNotTemplateWrapper)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of InlineNotTemplateWrapper_sentry", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of InlineNotTemplateWrapper_sentry", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: InlineNotTemplateWrapper_sentry::i_am_inline_not_template_wrapper_sentry", + ][::std::mem::offset_of!( + InlineNotTemplateWrapper_sentry, i_am_inline_not_template_wrapper_sentry + ) - 0usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of InlineNotTemplateWrapper", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of InlineNotTemplateWrapper", + ][::std::mem::align_of::() - 1usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct InlineTemplateWrapper { @@ -171,76 +115,45 @@ pub mod root { pub struct OuterDoubleWrapper_InnerDoubleWrapper { pub _address: u8, } - #[test] - fn bindgen_test_layout_OuterDoubleWrapper_InnerDoubleWrapper() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(OuterDoubleWrapper_InnerDoubleWrapper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!( - "Alignment of ", - stringify!(OuterDoubleWrapper_InnerDoubleWrapper), - ), - ); - } - #[test] - fn bindgen_test_layout_OuterDoubleWrapper() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(OuterDoubleWrapper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(OuterDoubleWrapper)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of OuterDoubleWrapper_InnerDoubleWrapper", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of OuterDoubleWrapper_InnerDoubleWrapper", + ][::std::mem::align_of::() - 1usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of OuterDoubleWrapper", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of OuterDoubleWrapper", + ][::std::mem::align_of::() - 1usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct OuterDoubleWrapper_InnerDoubleWrapper_sentry { pub i_am_double_wrapper_sentry: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_OuterDoubleWrapper_InnerDoubleWrapper_sentry() { - const UNINIT: ::std::mem::MaybeUninit< - OuterDoubleWrapper_InnerDoubleWrapper_sentry, - > = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!( - "Size of: ", - stringify!(OuterDoubleWrapper_InnerDoubleWrapper_sentry), - ), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!( - "Alignment of ", - stringify!(OuterDoubleWrapper_InnerDoubleWrapper_sentry), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).i_am_double_wrapper_sentry) as usize - - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(OuterDoubleWrapper_InnerDoubleWrapper_sentry), - "::", - stringify!(i_am_double_wrapper_sentry), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of OuterDoubleWrapper_InnerDoubleWrapper_sentry", + ][::std::mem::size_of::() + - 4usize]; + [ + "Alignment of OuterDoubleWrapper_InnerDoubleWrapper_sentry", + ][::std::mem::align_of::() + - 4usize]; + [ + "Offset of field: OuterDoubleWrapper_InnerDoubleWrapper_sentry::i_am_double_wrapper_sentry", + ][::std::mem::offset_of!( + OuterDoubleWrapper_InnerDoubleWrapper_sentry, i_am_double_wrapper_sentry + ) - 0usize]; + }; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct OuterDoubleInlineWrapper { @@ -256,82 +169,45 @@ pub mod root { pub struct OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry { pub i_am_double_wrapper_inline_sentry: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry() { - const UNINIT: ::std::mem::MaybeUninit< + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry", + ][::std::mem::size_of::< OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry, - > = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::< - OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry, - >(), - 4usize, - concat!( - "Size of: ", - stringify!(OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry), - ), - ); - assert_eq!( - ::std::mem::align_of::< - OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry, - >(), - 4usize, - concat!( - "Alignment of ", - stringify!(OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).i_am_double_wrapper_inline_sentry) - as usize - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry), - "::", - stringify!(i_am_double_wrapper_inline_sentry), - ), - ); - } - #[test] - fn bindgen_test_layout_OuterDoubleInlineWrapper_InnerDoubleInlineWrapper() { - assert_eq!( - ::std::mem::size_of::< - OuterDoubleInlineWrapper_InnerDoubleInlineWrapper, - >(), - 1usize, - concat!( - "Size of: ", - stringify!(OuterDoubleInlineWrapper_InnerDoubleInlineWrapper), - ), - ); - assert_eq!( - ::std::mem::align_of::< - OuterDoubleInlineWrapper_InnerDoubleInlineWrapper, - >(), - 1usize, - concat!( - "Alignment of ", - stringify!(OuterDoubleInlineWrapper_InnerDoubleInlineWrapper), - ), - ); - } - #[test] - fn bindgen_test_layout_OuterDoubleInlineWrapper() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(OuterDoubleInlineWrapper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(OuterDoubleInlineWrapper)), - ); - } + >() - 4usize]; + [ + "Alignment of OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry", + ][::std::mem::align_of::< + OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry, + >() - 4usize]; + [ + "Offset of field: OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry::i_am_double_wrapper_inline_sentry", + ][::std::mem::offset_of!( + OuterDoubleInlineWrapper_InnerDoubleInlineWrapper_sentry, + i_am_double_wrapper_inline_sentry + ) - 0usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of OuterDoubleInlineWrapper_InnerDoubleInlineWrapper", + ][::std::mem::size_of::() + - 1usize]; + [ + "Alignment of OuterDoubleInlineWrapper_InnerDoubleInlineWrapper", + ][::std::mem::align_of::() + - 1usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [ + "Size of OuterDoubleInlineWrapper", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of OuterDoubleInlineWrapper", + ][::std::mem::align_of::() - 1usize]; + }; } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -348,32 +224,12 @@ pub mod root { pub struct sentry { pub i_am_outside_namespace_sentry: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_sentry() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(sentry)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(sentry)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).i_am_outside_namespace_sentry) as usize - - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(sentry), - "::", - stringify!(i_am_outside_namespace_sentry), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of sentry"][::std::mem::size_of::() - 4usize]; + ["Alignment of sentry"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: sentry::i_am_outside_namespace_sentry", + ][::std::mem::offset_of!(sentry, i_am_outside_namespace_sentry) - 0usize]; + }; } diff --git a/bindgen-tests/tests/expectations/tests/size_t_template.rs b/bindgen-tests/tests/expectations/tests/size_t_template.rs index 3e37508b6a..9126c5071a 100644 --- a/bindgen-tests/tests/expectations/tests/size_t_template.rs +++ b/bindgen-tests/tests/expectations/tests/size_t_template.rs @@ -1,22 +1,22 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +/// If Bindgen could only determine the size and alignment of a +/// type, it is represented like this. +#[derive(PartialEq, Copy, Clone, Debug, Hash)] +#[repr(C)] +pub struct __BindgenOpaqueArray(pub [T; N]); +impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } +} #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct C { - pub arr: [u32; 3usize], -} -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 12usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(arr)), - ); + pub arr: __BindgenOpaqueArray, } +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 12usize]; + ["Alignment of C"][::std::mem::align_of::() - 4usize]; + ["Offset of field: C::arr"][::std::mem::offset_of!(C, arr) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/sorted_items.rs b/bindgen-tests/tests/expectations/tests/sorted_items.rs index e7da5e67fd..1c235fb31d 100644 --- a/bindgen-tests/tests/expectations/tests/sorted_items.rs +++ b/bindgen-tests/tests/expectations/tests/sorted_items.rs @@ -14,57 +14,21 @@ pub mod root { pub a: root::number, pub b: root::number, } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Point"][::std::mem::size_of::() - 8usize]; + ["Alignment of Point"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Point::x"][::std::mem::offset_of!(Point, x) - 0usize]; + ["Offset of field: Point::y"][::std::mem::offset_of!(Point, y) - 4usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Angle"][::std::mem::size_of::() - 8usize]; + ["Alignment of Angle"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Angle::a"][::std::mem::offset_of!(Angle, a) - 0usize]; + ["Offset of field: Angle::b"][::std::mem::offset_of!(Angle, b) - 4usize]; + }; pub const NUMBER: root::number = 42; - #[test] - fn bindgen_test_layout_Point() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Point)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Point)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Point), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Point), "::", stringify!(y)), - ); - } - #[test] - fn bindgen_test_layout_Angle() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Angle)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Angle)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Angle), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Angle), "::", stringify!(b)), - ); - } pub mod ns { pub type number = ::std::os::raw::c_int; #[repr(C)] @@ -79,83 +43,47 @@ pub mod root { pub a: root::ns::number, pub b: root::ns::number, } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Point"][::std::mem::size_of::() - 8usize]; + ["Alignment of Point"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Point::x"][::std::mem::offset_of!(Point, x) - 0usize]; + ["Offset of field: Point::y"][::std::mem::offset_of!(Point, y) - 4usize]; + }; + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of Angle"][::std::mem::size_of::() - 8usize]; + ["Alignment of Angle"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Angle::a"][::std::mem::offset_of!(Angle, a) - 0usize]; + ["Offset of field: Angle::b"][::std::mem::offset_of!(Angle, b) - 4usize]; + }; pub const NUMBER: root::ns::number = 42; - #[test] - fn bindgen_test_layout_Point() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Point)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Point)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Point), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Point), "::", stringify!(y)), - ); - } - #[test] - fn bindgen_test_layout_Angle() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Angle)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Angle)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Angle), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Angle), "::", stringify!(b)), - ); - } #[allow(unused_imports)] use self::super::super::root; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN2ns3fooEv"] pub fn foo() -> ::std::os::raw::c_int; } - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN2ns3barEi"] pub fn bar(x: root::ns::number) -> ::std::os::raw::c_int; } - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_ZN2ns3bazENS_5PointE"] pub fn baz(point: root::ns::Point) -> ::std::os::raw::c_int; } } #[allow(unused_imports)] use self::super::root; - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_Z3foov"] pub fn foo() -> ::std::os::raw::c_int; } - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_Z3bari"] pub fn bar(x: root::number) -> ::std::os::raw::c_int; } - extern "C" { + unsafe extern "C" { #[link_name = "\u{1}_Z3baz5Point"] pub fn baz(point: root::Point) -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/special-members.rs b/bindgen-tests/tests/expectations/tests/special-members.rs new file mode 100644 index 0000000000..4f54670c86 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/special-members.rs @@ -0,0 +1,51 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +#[derive(Debug, Default)] +pub struct A { + pub _address: u8, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of A"][::std::mem::size_of::() - 1usize]; + ["Alignment of A"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { + #[link_name = "\u{1}_ZN1AC1Ev"] + pub fn A_A(this: *mut A); +} +unsafe extern "C" { + #[link_name = "\u{1}_ZN1AC1ERS_"] + pub fn A_A1(this: *mut A, arg1: *mut A); +} +unsafe extern "C" { + #[link_name = "\u{1}_ZN1AC1EOS_"] + pub fn A_A2(this: *mut A, arg1: *mut A); +} +unsafe extern "C" { + #[link_name = "\u{1}_ZN1AD1Ev"] + pub fn A_A_destructor(this: *mut A); +} +impl A { + #[inline] + pub unsafe fn new() -> Self { + let mut __bindgen_tmp = ::std::mem::MaybeUninit::uninit(); + A_A(__bindgen_tmp.as_mut_ptr()); + __bindgen_tmp.assume_init() + } + #[inline] + pub unsafe fn new1(arg1: *mut A) -> Self { + let mut __bindgen_tmp = ::std::mem::MaybeUninit::uninit(); + A_A1(__bindgen_tmp.as_mut_ptr(), arg1); + __bindgen_tmp.assume_init() + } + #[inline] + pub unsafe fn new2(arg1: *mut A) -> Self { + let mut __bindgen_tmp = ::std::mem::MaybeUninit::uninit(); + A_A2(__bindgen_tmp.as_mut_ptr(), arg1); + __bindgen_tmp.assume_init() + } + #[inline] + pub unsafe fn destruct(&mut self) { + A_A_destructor(self) + } +} diff --git a/bindgen-tests/tests/expectations/tests/specific_receiver.rs b/bindgen-tests/tests/expectations/tests/specific_receiver.rs new file mode 100644 index 0000000000..ec001b12ad --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/specific_receiver.rs @@ -0,0 +1,28 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +pub struct Fish__bindgen_vtable { + pub Fish_swim: unsafe extern "C" fn(this: *mut Fish), +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct Fish { + pub vtable_: *const Fish__bindgen_vtable, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Fish"][::std::mem::size_of::() - 8usize]; + ["Alignment of Fish"][::std::mem::align_of::() - 8usize]; +}; +impl Default for Fish { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +unsafe extern "C" { + #[link_name = "\u{1}_ZN4Fish4swimEv"] + pub fn Fish_swim(this: *mut Fish); +} diff --git a/bindgen-tests/tests/expectations/tests/stdint_typedef.rs b/bindgen-tests/tests/expectations/tests/stdint_typedef.rs index 34c71831da..7cb1a2a8fb 100644 --- a/bindgen-tests/tests/expectations/tests/stdint_typedef.rs +++ b/bindgen-tests/tests/expectations/tests/stdint_typedef.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn fun() -> u64; } #[repr(C)] @@ -7,23 +7,9 @@ extern "C" { pub struct Struct { pub field: u64, } -#[test] -fn bindgen_test_layout_Struct() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Struct)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).field) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Struct), "::", stringify!(field)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Struct"][::std::mem::size_of::() - 8usize]; + ["Alignment of Struct"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Struct::field"][::std::mem::offset_of!(Struct, field) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/strings_array.rs b/bindgen-tests/tests/expectations/tests/strings_array.rs index 6f352b32ca..12543e59a8 100644 --- a/bindgen-tests/tests/expectations/tests/strings_array.rs +++ b/bindgen-tests/tests/expectations/tests/strings_array.rs @@ -1,4 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -pub const MY_STRING_UTF8: &'static [u8; 14] = b"Hello, world!\0"; -pub const MY_STRING_INTERIOR_NULL: &'static [u8; 7] = b"Hello,\0"; -pub const MY_STRING_NON_UTF8: &'static [u8; 7] = b"ABCDE\xFF\0"; +pub const MY_STRING_UTF8: &[u8; 14] = b"Hello, world!\0"; +pub const MY_STRING_INTERIOR_NULL: &[u8; 7] = b"Hello,\0"; +pub const MY_STRING_NON_UTF8: &[u8; 7] = b"ABCDE\xFF\0"; diff --git a/bindgen-tests/tests/expectations/tests/strings_cstr2.rs b/bindgen-tests/tests/expectations/tests/strings_cstr2.rs new file mode 100644 index 0000000000..2ce21f4374 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/strings_cstr2.rs @@ -0,0 +1,4 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +pub const MY_STRING_UTF8: &::std::ffi::CStr = c"Hello, world!"; +pub const MY_STRING_INTERIOR_NULL: &::std::ffi::CStr = c"Hello,"; +pub const MY_STRING_NON_UTF8: &::std::ffi::CStr = c"ABCDE\xFF"; diff --git a/bindgen-tests/tests/expectations/tests/strings_cstr2_2018.rs b/bindgen-tests/tests/expectations/tests/strings_cstr2_2018.rs new file mode 100644 index 0000000000..ca089cf130 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/strings_cstr2_2018.rs @@ -0,0 +1,13 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[allow(unsafe_code)] +pub const MY_STRING_UTF8: &::std::ffi::CStr = unsafe { + ::std::ffi::CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") +}; +#[allow(unsafe_code)] +pub const MY_STRING_INTERIOR_NULL: &::std::ffi::CStr = unsafe { + ::std::ffi::CStr::from_bytes_with_nul_unchecked(b"Hello,\0") +}; +#[allow(unsafe_code)] +pub const MY_STRING_NON_UTF8: &::std::ffi::CStr = unsafe { + ::std::ffi::CStr::from_bytes_with_nul_unchecked(b"ABCDE\xFF\0") +}; diff --git a/bindgen-tests/tests/expectations/tests/struct_containing_forward_declared_struct.rs b/bindgen-tests/tests/expectations/tests/struct_containing_forward_declared_struct.rs index 60c093c79a..0fe9024a5f 100644 --- a/bindgen-tests/tests/expectations/tests/struct_containing_forward_declared_struct.rs +++ b/bindgen-tests/tests/expectations/tests/struct_containing_forward_declared_struct.rs @@ -4,22 +4,12 @@ pub struct a { pub val_a: *mut b, } -#[test] -fn bindgen_test_layout_a() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 8usize, concat!("Size of: ", stringify!(a))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).val_a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(a), "::", stringify!(val_a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of a"][::std::mem::size_of::() - 8usize]; + ["Alignment of a"][::std::mem::align_of::() - 8usize]; + ["Offset of field: a::val_a"][::std::mem::offset_of!(a, val_a) - 0usize]; +}; impl Default for a { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -34,19 +24,9 @@ impl Default for a { pub struct b { pub val_b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_b() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(b))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(b)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).val_b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(b), "::", stringify!(val_b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of b"][::std::mem::size_of::() - 4usize]; + ["Alignment of b"][::std::mem::align_of::() - 4usize]; + ["Offset of field: b::val_b"][::std::mem::offset_of!(b, val_b) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/struct_typedef.rs b/bindgen-tests/tests/expectations/tests/struct_typedef.rs index 2c0039e3f0..bc12a1bce8 100644 --- a/bindgen-tests/tests/expectations/tests/struct_typedef.rs +++ b/bindgen-tests/tests/expectations/tests/struct_typedef.rs @@ -4,61 +4,31 @@ pub struct typedef_named_struct { pub has_name: bool, } -#[test] -fn bindgen_test_layout_typedef_named_struct() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(typedef_named_struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(typedef_named_struct)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).has_name) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(typedef_named_struct), - "::", - stringify!(has_name), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of typedef_named_struct", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of typedef_named_struct", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: typedef_named_struct::has_name", + ][::std::mem::offset_of!(typedef_named_struct, has_name) - 0usize]; +}; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct _bindgen_ty_1 { pub no_name: *mut ::std::os::raw::c_void, } -#[test] -fn bindgen_test_layout__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit<_bindgen_ty_1> = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::<_bindgen_ty_1>(), - 8usize, - concat!("Size of: ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::<_bindgen_ty_1>(), - 8usize, - concat!("Alignment of ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).no_name) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(_bindgen_ty_1), - "::", - stringify!(no_name), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of _bindgen_ty_1"][::std::mem::size_of::<_bindgen_ty_1>() - 8usize]; + ["Alignment of _bindgen_ty_1"][::std::mem::align_of::<_bindgen_ty_1>() - 8usize]; + [ + "Offset of field: _bindgen_ty_1::no_name", + ][::std::mem::offset_of!(_bindgen_ty_1, no_name) - 0usize]; +}; impl Default for _bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/struct_typedef_ns.rs b/bindgen-tests/tests/expectations/tests/struct_typedef_ns.rs index aabe23b18e..82f93dfd16 100644 --- a/bindgen-tests/tests/expectations/tests/struct_typedef_ns.rs +++ b/bindgen-tests/tests/expectations/tests/struct_typedef_ns.rs @@ -11,31 +11,16 @@ pub mod root { pub struct typedef_struct { pub foo: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_typedef_struct() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(typedef_struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(typedef_struct)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(typedef_struct), - "::", - stringify!(foo), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of typedef_struct"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of typedef_struct", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: typedef_struct::foo", + ][::std::mem::offset_of!(typedef_struct, foo) - 0usize]; + }; #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum typedef_enum { @@ -50,31 +35,16 @@ pub mod root { pub struct typedef_struct { pub foo: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_typedef_struct() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(typedef_struct)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(typedef_struct)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(typedef_struct), - "::", - stringify!(foo), - ), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of typedef_struct"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of typedef_struct", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: typedef_struct::foo", + ][::std::mem::offset_of!(typedef_struct, foo) - 0usize]; + }; #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum typedef_enum { diff --git a/bindgen-tests/tests/expectations/tests/struct_with_anon_struct.rs b/bindgen-tests/tests/expectations/tests/struct_with_anon_struct.rs index d5ea2224b4..51aa19c572 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_anon_struct.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_anon_struct.rs @@ -10,48 +10,22 @@ pub struct foo__bindgen_ty_1 { pub a: ::std::os::raw::c_int, pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/struct_with_anon_struct_array.rs b/bindgen-tests/tests/expectations/tests/struct_with_anon_struct_array.rs index ba3f82a86f..930e6b9aba 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_anon_struct_array.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_anon_struct_array.rs @@ -11,84 +11,42 @@ pub struct foo__bindgen_ty_1 { pub a: ::std::os::raw::c_int, pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 4usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo__bindgen_ty_2 { pub a: ::std::os::raw::c_int, pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_2), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_2), "::", stringify!(b)), - ); -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 208usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_2"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of foo__bindgen_ty_2", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_2::a", + ][::std::mem::offset_of!(foo__bindgen_ty_2, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_2::b", + ][::std::mem::offset_of!(foo__bindgen_ty_2, b) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 208usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; + ["Offset of field: foo::baz"][::std::mem::offset_of!(foo, baz) - 16usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/struct_with_anon_struct_pointer.rs b/bindgen-tests/tests/expectations/tests/struct_with_anon_struct_pointer.rs index 77a89934b0..6bdee34590 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_anon_struct_pointer.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_anon_struct_pointer.rs @@ -10,51 +10,25 @@ pub struct foo__bindgen_ty_1 { pub a: ::std::os::raw::c_int, pub b: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/struct_with_anon_union.rs b/bindgen-tests/tests/expectations/tests/struct_with_anon_union.rs index 506b6a8819..6520163259 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_anon_union.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_anon_union.rs @@ -10,31 +10,19 @@ pub union foo__bindgen_ty_1 { pub a: ::std::os::raw::c_uint, pub b: ::std::os::raw::c_ushort, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 0usize]; +}; impl Default for foo__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -44,26 +32,12 @@ impl Default for foo__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/struct_with_anon_union_1_0.rs b/bindgen-tests/tests/expectations/tests/struct_with_anon_union_1_0.rs deleted file mode 100644 index 8bab61e3b7..0000000000 --- a/bindgen-tests/tests/expectations/tests/struct_with_anon_union_1_0.rs +++ /dev/null @@ -1,111 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub bar: foo__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1 { - pub a: __BindgenUnionField<::std::os::raw::c_uint>, - pub b: __BindgenUnionField<::std::os::raw::c_ushort>, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -impl Clone for foo__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_struct.rs b/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_struct.rs index 981dd648be..29cf382e5f 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_struct.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_struct.rs @@ -10,41 +10,21 @@ pub struct foo__bindgen_ty_1 { pub a: ::std::os::raw::c_uint, pub b: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -#[test] -fn bindgen_test_layout_foo() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_union.rs b/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_union.rs index 3d0175354f..2f95e0f5e0 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_union.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_union.rs @@ -10,31 +10,19 @@ pub union foo__bindgen_ty_1 { pub a: ::std::os::raw::c_uint, pub b: ::std::os::raw::c_ushort, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 0usize]; +}; impl Default for foo__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -44,19 +32,11 @@ impl Default for foo__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_foo() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_union_1_0.rs b/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_union_1_0.rs deleted file mode 100644 index ae2ff33377..0000000000 --- a/bindgen-tests/tests/expectations/tests/struct_with_anon_unnamed_union_1_0.rs +++ /dev/null @@ -1,104 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub __bindgen_anon_1: foo__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1 { - pub a: __BindgenUnionField<::std::os::raw::c_uint>, - pub b: __BindgenUnionField<::std::os::raw::c_ushort>, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -impl Clone for foo__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/struct_with_bitfields.rs b/bindgen-tests/tests/expectations/tests/struct_with_bitfields.rs index 6a6b17e341..23588ee7da 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_bitfields.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_bitfields.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] @@ -92,26 +154,12 @@ pub struct bitfield { pub _bitfield_align_2: [u32; 0], pub _bitfield_2: __BindgenBitfieldUnit<[u8; 8usize]>, } -#[test] -fn bindgen_test_layout_bitfield() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(bitfield)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bitfield)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).e) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(bitfield), "::", stringify!(e)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bitfield"][::std::mem::size_of::() - 16usize]; + ["Alignment of bitfield"][::std::mem::align_of::() - 4usize]; + ["Offset of field: bitfield::e"][::std::mem::offset_of!(bitfield, e) - 4usize]; +}; impl bitfield { #[inline] pub fn a(&self) -> ::std::os::raw::c_ushort { @@ -125,6 +173,31 @@ impl bitfield { } } #[inline] + pub unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn b(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u16) } } @@ -136,6 +209,31 @@ impl bitfield { } } #[inline] + pub unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 1usize, 1u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn c(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u16) } } @@ -147,6 +245,31 @@ impl bitfield { } } #[inline] + pub unsafe fn c_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 2usize, 1u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_c_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn d(&self) -> ::std::os::raw::c_ushort { unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 2u8) as u16) } } @@ -158,6 +281,31 @@ impl bitfield { } } #[inline] + pub unsafe fn d_raw(this: *const Self) -> ::std::os::raw::c_ushort { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 6usize, 2u8) + as u16, + ) + } + } + #[inline] + pub unsafe fn set_d_raw(this: *mut Self, val: ::std::os::raw::c_ushort) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 2u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( a: ::std::os::raw::c_ushort, b: ::std::os::raw::c_ushort, @@ -215,6 +363,31 @@ impl bitfield { } } #[inline] + pub unsafe fn f_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 0usize, 2u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_f_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] pub fn g(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_2.get(32usize, 32u8) as u32) } } @@ -226,6 +399,31 @@ impl bitfield { } } #[inline] + pub unsafe fn g_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 32usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_g_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 8usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 32usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_2( f: ::std::os::raw::c_uint, g: ::std::os::raw::c_uint, diff --git a/bindgen-tests/tests/expectations/tests/struct_with_derive_debug.rs b/bindgen-tests/tests/expectations/tests/struct_with_derive_debug.rs index b84fa7b2c0..b472666081 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_derive_debug.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_derive_debug.rs @@ -8,20 +8,16 @@ pub struct LittleArray { fn bindgen_test_layout_LittleArray() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 128usize, - concat!("Size of: ", stringify!(LittleArray)), - ); + assert_eq!(::std::mem::size_of::(), 128usize, "Size of LittleArray"); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(LittleArray)), + "Alignment of LittleArray", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(LittleArray), "::", stringify!(a)), + "Offset of field: LittleArray::a", ); } #[repr(C)] @@ -33,20 +29,12 @@ pub struct BigArray { fn bindgen_test_layout_BigArray() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 132usize, - concat!("Size of: ", stringify!(BigArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(BigArray)), - ); + assert_eq!(::std::mem::size_of::(), 132usize, "Size of BigArray"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of BigArray"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(BigArray), "::", stringify!(a)), + "Offset of field: BigArray::a", ); } impl Default for BigArray { @@ -70,17 +58,17 @@ fn bindgen_test_layout_WithLittleArray() { assert_eq!( ::std::mem::size_of::(), 128usize, - concat!("Size of: ", stringify!(WithLittleArray)), + "Size of WithLittleArray", ); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(WithLittleArray)), + "Alignment of WithLittleArray", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(WithLittleArray), "::", stringify!(a)), + "Offset of field: WithLittleArray::a", ); } #[repr(C)] @@ -92,20 +80,16 @@ pub struct WithBigArray { fn bindgen_test_layout_WithBigArray() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 132usize, - concat!("Size of: ", stringify!(WithBigArray)), - ); + assert_eq!(::std::mem::size_of::(), 132usize, "Size of WithBigArray"); assert_eq!( ::std::mem::align_of::(), 4usize, - concat!("Alignment of ", stringify!(WithBigArray)), + "Alignment of WithBigArray", ); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(WithBigArray), "::", stringify!(a)), + "Offset of field: WithBigArray::a", ); } impl Default for WithBigArray { diff --git a/bindgen-tests/tests/expectations/tests/struct_with_large_array.rs b/bindgen-tests/tests/expectations/tests/struct_with_large_array.rs index 74b409235d..eda7cadb46 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_large_array.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_large_array.rs @@ -8,16 +8,12 @@ pub struct S { fn bindgen_test_layout_S() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 33usize, concat!("Size of: ", stringify!(S))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(S)), - ); + assert_eq!(::std::mem::size_of::(), 33usize, "Size of S"); + assert_eq!(::std::mem::align_of::(), 1usize, "Alignment of S"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).large_array) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(S), "::", stringify!(large_array)), + "Offset of field: S::large_array", ); } impl Default for S { @@ -31,8 +27,8 @@ impl Default for S { } #[repr(C)] pub struct ST { - pub large_array: [T; 33usize], pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub large_array: [T; 33usize], } impl Default for ST { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/struct_with_nesting.rs b/bindgen-tests/tests/expectations/tests/struct_with_nesting.rs index 1bcba5a154..369384e88c 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_nesting.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_nesting.rs @@ -18,41 +18,21 @@ pub struct foo__bindgen_ty_1__bindgen_ty_1 { pub c1: ::std::os::raw::c_ushort, pub c2: ::std::os::raw::c_ushort, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(c1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c2) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(c2), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of foo__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_1::c1", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_1, c1) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_1::c2", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_1, c2) - 2usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo__bindgen_ty_1__bindgen_ty_2 { @@ -61,81 +41,37 @@ pub struct foo__bindgen_ty_1__bindgen_ty_2 { pub d3: ::std::os::raw::c_uchar, pub d4: ::std::os::raw::c_uchar, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(d1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d2) as usize - ptr as usize }, - 1usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(d2), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d3) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(d3), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d4) as usize - ptr as usize }, - 3usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(d4), - ), - ); -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of foo__bindgen_ty_1__bindgen_ty_2", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1__bindgen_ty_2", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_2::d1", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_2, d1) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_2::d2", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_2, d2) - 1usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_2::d3", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_2, d3) - 2usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_2::d4", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_2, d4) - 3usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 0usize]; +}; impl Default for foo__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -145,26 +81,12 @@ impl Default for foo__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::a"][::std::mem::offset_of!(foo, a) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/struct_with_nesting_1_0.rs b/bindgen-tests/tests/expectations/tests/struct_with_nesting_1_0.rs deleted file mode 100644 index 6d8a5b97ae..0000000000 --- a/bindgen-tests/tests/expectations/tests/struct_with_nesting_1_0.rs +++ /dev/null @@ -1,222 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub a: ::std::os::raw::c_uint, - pub __bindgen_anon_1: foo__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1 { - pub b: __BindgenUnionField<::std::os::raw::c_uint>, - pub __bindgen_anon_1: __BindgenUnionField, - pub __bindgen_anon_2: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1__bindgen_ty_1 { - pub c1: ::std::os::raw::c_ushort, - pub c2: ::std::os::raw::c_ushort, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(c1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c2) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(c2), - ), - ); -} -impl Clone for foo__bindgen_ty_1__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1__bindgen_ty_2 { - pub d1: ::std::os::raw::c_uchar, - pub d2: ::std::os::raw::c_uchar, - pub d3: ::std::os::raw::c_uchar, - pub d4: ::std::os::raw::c_uchar, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(d1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d2) as usize - ptr as usize }, - 1usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(d2), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d3) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(d3), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d4) as usize - ptr as usize }, - 3usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(d4), - ), - ); -} -impl Clone for foo__bindgen_ty_1__bindgen_ty_2 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -impl Clone for foo__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/struct_with_packing.rs b/bindgen-tests/tests/expectations/tests/struct_with_packing.rs index 252756e86c..2687f9750b 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_packing.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_packing.rs @@ -5,24 +5,10 @@ pub struct a { pub b: ::std::os::raw::c_char, pub c: ::std::os::raw::c_short, } -#[test] -fn bindgen_test_layout_a() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!(::std::mem::size_of::(), 3usize, concat!("Size of: ", stringify!(a))); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(a), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 1usize, - concat!("Offset of field: ", stringify!(a), "::", stringify!(c)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of a"][::std::mem::size_of::() - 3usize]; + ["Alignment of a"][::std::mem::align_of::() - 1usize]; + ["Offset of field: a::b"][::std::mem::offset_of!(a, b) - 0usize]; + ["Offset of field: a::c"][::std::mem::offset_of!(a, c) - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/struct_with_struct.rs b/bindgen-tests/tests/expectations/tests/struct_with_struct.rs index db6f32a57e..40c3972600 100644 --- a/bindgen-tests/tests/expectations/tests/struct_with_struct.rs +++ b/bindgen-tests/tests/expectations/tests/struct_with_struct.rs @@ -10,48 +10,22 @@ pub struct foo__bindgen_ty_1 { pub x: ::std::os::raw::c_uint, pub y: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(y)), - ); -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::x", + ][::std::mem::offset_of!(foo__bindgen_ty_1, x) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::y", + ][::std::mem::offset_of!(foo__bindgen_ty_1, y) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-0.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-0.rs index 6ca9b11ec6..ba8980be00 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-0.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-0.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct UsesTemplateParameter { - pub t: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, } impl Default for UsesTemplateParameter { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-10.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-10.rs index 778ac4a2a3..a4e5d0ce82 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-10.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-10.rs @@ -2,19 +2,19 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct DoublyIndirectUsage { - pub doubly_indirect: DoublyIndirectUsage_IndirectUsage, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub doubly_indirect: DoublyIndirectUsage_IndirectUsage, } pub type DoublyIndirectUsage_Aliased = T; pub type DoublyIndirectUsage_Typedefed = U; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct DoublyIndirectUsage_IndirectUsage { - pub member: DoublyIndirectUsage_Aliased, - pub another: DoublyIndirectUsage_Typedefed, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member: DoublyIndirectUsage_Aliased, + pub another: DoublyIndirectUsage_Typedefed, } impl Default for DoublyIndirectUsage_IndirectUsage { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-12.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-12.rs index d4d403f1da..7f3a306b6b 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-12.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-12.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct BaseUsesT { - pub t: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: *mut T, } impl Default for BaseUsesT { fn default() -> Self { @@ -17,9 +17,9 @@ impl Default for BaseUsesT { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct CrtpUsesU { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _base: BaseUsesT>, pub usage: U, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for CrtpUsesU { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-13.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-13.rs index 204bb1d965..185f16be11 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-13.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-13.rs @@ -7,9 +7,9 @@ pub struct BaseIgnoresT { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct CrtpUsesU { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _base: BaseIgnoresT, pub usage: U, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for CrtpUsesU { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-15.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-15.rs index c6d7f71d17..fced6dc58c 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-15.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-15.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct BaseUsesT { - pub usage: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub usage: *mut T, } impl Default for BaseUsesT { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-2.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-2.rs index ea24b9ea82..4c671ce2ab 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-2.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-2.rs @@ -2,14 +2,14 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct UsesTemplateParameter { - pub t: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct UsesTemplateParameter_AlsoUsesTemplateParameter { - pub also: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub also: T, } impl Default for UsesTemplateParameter_AlsoUsesTemplateParameter { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-3.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-3.rs index ab7121bca9..511365e656 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-3.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-3.rs @@ -2,16 +2,16 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct UsesTemplateParameter { - pub t: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct UsesTemplateParameter_AlsoUsesTemplateParameterAndMore { - pub also: T, - pub more: U, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub also: T, + pub more: U, } impl Default for UsesTemplateParameter_AlsoUsesTemplateParameterAndMore { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-4.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-4.rs index 0136af8b45..5655a6d260 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-4.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-4.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct UsesTemplateParameter { - pub t: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-5.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-5.rs index da363e8058..5049559b33 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-5.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-5.rs @@ -2,8 +2,8 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct IndirectlyUsesTemplateParameter { - pub aliased: IndirectlyUsesTemplateParameter_Aliased, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub aliased: IndirectlyUsesTemplateParameter_Aliased, } pub type IndirectlyUsesTemplateParameter_Aliased = T; impl Default for IndirectlyUsesTemplateParameter { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-7.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-7.rs index 477fc5efe1..1552ae852f 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-7.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-7.rs @@ -2,10 +2,10 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct DoesNotUseU { - pub t: T, - pub v: V, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, + pub v: V, } impl Default for DoesNotUseU { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-8.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-8.rs index 700f06c431..61de18a833 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-8.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-8.rs @@ -2,10 +2,10 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct IndirectUsage { - pub member1: IndirectUsage_Typedefed, - pub member2: IndirectUsage_Aliased, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member1: IndirectUsage_Typedefed, + pub member2: IndirectUsage_Aliased, } pub type IndirectUsage_Typedefed = T; pub type IndirectUsage_Aliased = U; diff --git a/bindgen-tests/tests/expectations/tests/template-param-usage-9.rs b/bindgen-tests/tests/expectations/tests/template-param-usage-9.rs index 6e62dccd41..ff0eedc8ae 100644 --- a/bindgen-tests/tests/expectations/tests/template-param-usage-9.rs +++ b/bindgen-tests/tests/expectations/tests/template-param-usage-9.rs @@ -9,10 +9,10 @@ pub type DoesNotUse_Typedefed = U; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct DoesNotUse_IndirectUsage { - pub member: DoesNotUse_Aliased, - pub another: DoesNotUse_Typedefed, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member: DoesNotUse_Aliased, + pub another: DoesNotUse_Typedefed, } impl Default for DoesNotUse_IndirectUsage { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template.rs b/bindgen-tests/tests/expectations/tests/template.rs index d43d4dd1a8..94678cb49e 100644 --- a/bindgen-tests/tests/expectations/tests/template.rs +++ b/bindgen-tests/tests/expectations/tests/template.rs @@ -2,10 +2,10 @@ #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct Foo { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub m_member: T, pub m_member_ptr: *mut T, pub m_member_arr: [T; 1usize], - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for Foo { fn default() -> Self { @@ -19,8 +19,8 @@ impl Default for Foo { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct B { - pub m_member: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub m_member: T, } impl Default for B { fn default() -> Self { @@ -31,7 +31,7 @@ impl Default for B { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z3bar3FooIiiE"] pub fn bar(foo: Foo<::std::os::raw::c_int>); } @@ -60,108 +60,37 @@ pub struct C { pub mArrayRef: B<*mut [::std::os::raw::c_int; 1usize]>, pub mBConstArray: B<[::std::os::raw::c_int; 1usize]>, } -#[test] -fn bindgen_test_layout_C() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 104usize, - concat!("Size of: ", stringify!(C)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(C)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mB) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mB)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBConstPtr) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBConstPtr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBConstStructPtr) as usize - ptr as usize }, - 16usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBConstStructPtr)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mBConstStructPtrArray) as usize - ptr as usize - }, - 24usize, - concat!( - "Offset of field: ", - stringify!(C), - "::", - stringify!(mBConstStructPtrArray), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBConst) as usize - ptr as usize }, - 32usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBConst)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBVolatile) as usize - ptr as usize }, - 36usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBVolatile)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBConstBool) as usize - ptr as usize }, - 40usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBConstBool)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBConstChar) as usize - ptr as usize }, - 42usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBConstChar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBArray) as usize - ptr as usize }, - 44usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBPtrArray) as usize - ptr as usize }, - 48usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBPtrArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBArrayPtr) as usize - ptr as usize }, - 56usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBArrayPtr)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBRef) as usize - ptr as usize }, - 64usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBRef)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBConstRef) as usize - ptr as usize }, - 72usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBConstRef)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mPtrRef) as usize - ptr as usize }, - 80usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mPtrRef)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mArrayRef) as usize - ptr as usize }, - 88usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mArrayRef)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBConstArray) as usize - ptr as usize }, - 96usize, - concat!("Offset of field: ", stringify!(C), "::", stringify!(mBConstArray)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 104usize]; + ["Alignment of C"][::std::mem::align_of::() - 8usize]; + ["Offset of field: C::mB"][::std::mem::offset_of!(C, mB) - 0usize]; + ["Offset of field: C::mBConstPtr"][::std::mem::offset_of!(C, mBConstPtr) - 8usize]; + [ + "Offset of field: C::mBConstStructPtr", + ][::std::mem::offset_of!(C, mBConstStructPtr) - 16usize]; + [ + "Offset of field: C::mBConstStructPtrArray", + ][::std::mem::offset_of!(C, mBConstStructPtrArray) - 24usize]; + ["Offset of field: C::mBConst"][::std::mem::offset_of!(C, mBConst) - 32usize]; + ["Offset of field: C::mBVolatile"][::std::mem::offset_of!(C, mBVolatile) - 36usize]; + [ + "Offset of field: C::mBConstBool", + ][::std::mem::offset_of!(C, mBConstBool) - 40usize]; + [ + "Offset of field: C::mBConstChar", + ][::std::mem::offset_of!(C, mBConstChar) - 42usize]; + ["Offset of field: C::mBArray"][::std::mem::offset_of!(C, mBArray) - 44usize]; + ["Offset of field: C::mBPtrArray"][::std::mem::offset_of!(C, mBPtrArray) - 48usize]; + ["Offset of field: C::mBArrayPtr"][::std::mem::offset_of!(C, mBArrayPtr) - 56usize]; + ["Offset of field: C::mBRef"][::std::mem::offset_of!(C, mBRef) - 64usize]; + ["Offset of field: C::mBConstRef"][::std::mem::offset_of!(C, mBConstRef) - 72usize]; + ["Offset of field: C::mPtrRef"][::std::mem::offset_of!(C, mPtrRef) - 80usize]; + ["Offset of field: C::mArrayRef"][::std::mem::offset_of!(C, mArrayRef) - 88usize]; + [ + "Offset of field: C::mBConstArray", + ][::std::mem::offset_of!(C, mBConstArray) - 96usize]; +}; impl Default for C { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -180,9 +109,9 @@ pub type D_MyFoo = Foo<::std::os::raw::c_int>; #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct D_U { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub m_nested_foo: D_MyFoo, pub m_baz: Z, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for D_U { fn default() -> Self { @@ -205,10 +134,10 @@ impl Default for D { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Rooted { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub prev: *mut T, pub next: *mut Rooted<*mut ::std::os::raw::c_void>, pub ptr: T, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for Rooted { fn default() -> Self { @@ -224,26 +153,14 @@ impl Default for Rooted { pub struct RootedContainer { pub root: Rooted<*mut ::std::os::raw::c_void>, } -#[test] -fn bindgen_test_layout_RootedContainer() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(RootedContainer)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(RootedContainer)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).root) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(RootedContainer), "::", stringify!(root)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of RootedContainer"][::std::mem::size_of::() - 24usize]; + ["Alignment of RootedContainer"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: RootedContainer::root", + ][::std::mem::offset_of!(RootedContainer, root) - 0usize]; +}; impl Default for RootedContainer { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -257,8 +174,8 @@ pub type WithDtorIntFwd = WithDtor<::std::os::raw::c_int>; #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct WithDtor { - pub member: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub member: T, } impl Default for WithDtor { fn default() -> Self { @@ -274,31 +191,16 @@ impl Default for WithDtor { pub struct PODButContainsDtor { pub member: WithDtorIntFwd, } -#[test] -fn bindgen_test_layout_PODButContainsDtor() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(PODButContainsDtor)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(PODButContainsDtor)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).member) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(PODButContainsDtor), - "::", - stringify!(member), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of PODButContainsDtor"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of PODButContainsDtor", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: PODButContainsDtor::member", + ][::std::mem::offset_of!(PODButContainsDtor, member) - 0usize]; +}; impl Default for PODButContainsDtor { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -319,32 +221,20 @@ pub struct Opaque { pub struct POD { pub opaque_member: u32, } -#[test] -fn bindgen_test_layout_POD() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(POD)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(POD)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).opaque_member) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(POD), "::", stringify!(opaque_member)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of POD"][::std::mem::size_of::() - 4usize]; + ["Alignment of POD"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: POD::opaque_member", + ][::std::mem::offset_of!(POD, opaque_member) - 0usize]; +}; ///
#[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct NestedReplaced { - pub buff: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub buff: *mut T, } impl Default for NestedReplaced { fn default() -> Self { @@ -358,8 +248,8 @@ impl Default for NestedReplaced { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct NestedBase { - pub buff: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub buff: *mut T, } impl Default for NestedBase { fn default() -> Self { @@ -373,10 +263,10 @@ impl Default for NestedBase { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct NestedContainer { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub c: T, pub nested: NestedReplaced, pub inc: Incomplete, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for NestedContainer { fn default() -> Self { @@ -390,8 +280,8 @@ impl Default for NestedContainer { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Incomplete { - pub d: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub d: T, } impl Default for Incomplete { fn default() -> Self { @@ -407,19 +297,11 @@ impl Default for Incomplete { pub struct Untemplated { pub _address: u8, } -#[test] -fn bindgen_test_layout_Untemplated() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Untemplated)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Untemplated)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Untemplated"][::std::mem::size_of::() - 1usize]; + ["Alignment of Untemplated"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct Templated { @@ -432,8 +314,8 @@ pub struct Templated { #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct ReplacedWithoutDestructor { - pub buff: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub buff: *mut T, } impl Default for ReplacedWithoutDestructor { fn default() -> Self { @@ -447,8 +329,8 @@ impl Default for ReplacedWithoutDestructor { #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct ShouldNotBeCopiable { - pub m_member: ReplacedWithoutDestructor, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub m_member: ReplacedWithoutDestructor, } impl Default for ShouldNotBeCopiable { fn default() -> Self { @@ -462,8 +344,8 @@ impl Default for ShouldNotBeCopiable { #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct ShouldNotBeCopiableAsWell { - pub m_member: ReplacedWithoutDestructorFwd, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub m_member: ReplacedWithoutDestructorFwd, } impl Default for ShouldNotBeCopiableAsWell { fn default() -> Self { @@ -481,8 +363,8 @@ impl Default for ShouldNotBeCopiableAsWell { #[repr(C)] #[derive(Debug, Hash, PartialEq, Eq)] pub struct ReplacedWithoutDestructorFwd { - pub buff: *mut T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub buff: *mut T, } impl Default for ReplacedWithoutDestructorFwd { fn default() -> Self { @@ -493,390 +375,192 @@ impl Default for ReplacedWithoutDestructorFwd { } } } -#[test] -fn __bindgen_test_layout_Foo_open0_int_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 24usize, - concat!( - "Size of template specialization: ", - stringify!(Foo < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(Foo < ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_unsigned_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(B < ::std::os::raw::c_uint >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < ::std::os::raw::c_uint >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_ptr_const_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < * const ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < * const ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_ptr_const_mozilla__Foo_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < * const mozilla_Foo >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < * const mozilla_Foo >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_array1_ptr_const_mozilla__Foo_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < [* const mozilla_Foo; 1usize] >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < [* const mozilla_Foo; 1usize] >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_const_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(B < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_volatile_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(B < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_const_bool_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 1usize, - concat!("Size of template specialization: ", stringify!(B < bool >)), - ); - assert_eq!( - ::std::mem::align_of::>(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(B < bool >)), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_const_char16_t_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 2usize, - concat!("Size of template specialization: ", stringify!(B < u16 >)), - ); - assert_eq!( - ::std::mem::align_of::>(), - 2usize, - concat!("Alignment of template specialization: ", stringify!(B < u16 >)), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_array1_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(B < [::std::os::raw::c_int; 1usize] >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < [::std::os::raw::c_int; 1usize] >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_array1_ptr_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < [* mut ::std::os::raw::c_int; 1usize] >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < [* mut ::std::os::raw::c_int; 1usize] >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_ptr_array1_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < * mut [::std::os::raw::c_int; 1usize] >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < * mut [::std::os::raw::c_int; 1usize] >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_ref_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < * mut ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < * mut ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_ref_const_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < * const ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < * const ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_ref_ptr_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < * mut * mut ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < * mut * mut ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_ref_array1_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(B < * mut [::std::os::raw::c_int; 1usize] >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < * mut [::std::os::raw::c_int; 1usize] >), - ), - ); -} -#[test] -fn __bindgen_test_layout_B_open0_array1_const_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(B < [::std::os::raw::c_int; 1usize] >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(B < [::std::os::raw::c_int; 1usize] >), - ), - ); -} -#[test] -fn __bindgen_test_layout_Foo_open0_int_int_close0_instantiation_1() { - assert_eq!( - ::std::mem::size_of::>(), - 24usize, - concat!( - "Size of template specialization: ", - stringify!(Foo < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(Foo < ::std::os::raw::c_int >), - ), - ); -} -#[test] -fn __bindgen_test_layout_Rooted_open0_ptr_void_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 24usize, - concat!( - "Size of template specialization: ", - stringify!(Rooted < * mut ::std::os::raw::c_void >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(Rooted < * mut ::std::os::raw::c_void >), - ), - ); -} -#[test] -fn __bindgen_test_layout_Rooted_open0_ptr_void_close0_instantiation_1() { - assert_eq!( - ::std::mem::size_of::>(), - 24usize, - concat!( - "Size of template specialization: ", - stringify!(Rooted < * mut ::std::os::raw::c_void >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(Rooted < * mut ::std::os::raw::c_void >), - ), - ); -} -#[test] -fn __bindgen_test_layout_WithDtor_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(WithDtor < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(WithDtor < ::std::os::raw::c_int >), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Foo_open0_int_int_close0", + ][::std::mem::size_of::>() - 24usize]; + [ + "Align of template specialization: Foo_open0_int_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_unsigned_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: B_open0_unsigned_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_ptr_const_int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_ptr_const_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_ptr_const_mozilla__Foo_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_ptr_const_mozilla__Foo_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_array1_ptr_const_mozilla__Foo_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_array1_ptr_const_mozilla__Foo_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_const_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: B_open0_const_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_volatile_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: B_open0_volatile_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_const_bool_close0", + ][::std::mem::size_of::>() - 1usize]; + [ + "Align of template specialization: B_open0_const_bool_close0", + ][::std::mem::align_of::>() - 1usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_const_char16_t_close0", + ][::std::mem::size_of::>() - 2usize]; + [ + "Align of template specialization: B_open0_const_char16_t_close0", + ][::std::mem::align_of::>() - 2usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_array1_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: B_open0_array1_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_array1_ptr_int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_array1_ptr_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_ptr_array1_int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_ptr_array1_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_ref_int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_ref_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_ref_const_int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_ref_const_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_ref_ptr_int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_ref_ptr_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_ref_array1_int_close0", + ][::std::mem::size_of::>() - 8usize]; + [ + "Align of template specialization: B_open0_ref_array1_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: B_open0_array1_const_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: B_open0_array1_const_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Foo_open0_int_int_close0", + ][::std::mem::size_of::>() - 24usize]; + [ + "Align of template specialization: Foo_open0_int_int_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Rooted_open0_ptr_void_close0", + ][::std::mem::size_of::>() - 24usize]; + [ + "Align of template specialization: Rooted_open0_ptr_void_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Rooted_open0_ptr_void_close0", + ][::std::mem::size_of::>() - 24usize]; + [ + "Align of template specialization: Rooted_open0_ptr_void_close0", + ][::std::mem::align_of::>() - 8usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: WithDtor_open0_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: WithDtor_open0_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/template_alias.rs b/bindgen-tests/tests/expectations/tests/template_alias.rs index d286cca3c6..b270c9f3a4 100644 --- a/bindgen-tests/tests/expectations/tests/template_alias.rs +++ b/bindgen-tests/tests/expectations/tests/template_alias.rs @@ -3,8 +3,8 @@ pub type JS_detail_Wrapped = T; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct JS_Rooted { - pub ptr: JS_detail_Wrapped, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub ptr: JS_detail_Wrapped, } impl Default for JS_Rooted { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template_alias_namespace.rs b/bindgen-tests/tests/expectations/tests/template_alias_namespace.rs index d0dfa78596..0aa5fc679a 100644 --- a/bindgen-tests/tests/expectations/tests/template_alias_namespace.rs +++ b/bindgen-tests/tests/expectations/tests/template_alias_namespace.rs @@ -14,8 +14,8 @@ pub mod root { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Rooted { - pub ptr: root::JS::detail::Wrapped, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub ptr: root::JS::detail::Wrapped, } impl Default for Rooted { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/template_instantiation_with_fn_local_type.rs b/bindgen-tests/tests/expectations/tests/template_instantiation_with_fn_local_type.rs index c6da8c26c7..085278e603 100644 --- a/bindgen-tests/tests/expectations/tests/template_instantiation_with_fn_local_type.rs +++ b/bindgen-tests/tests/expectations/tests/template_instantiation_with_fn_local_type.rs @@ -4,87 +4,55 @@ pub struct Foo { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z1fv"] pub fn f(); } -#[test] -fn __bindgen_test_layout_Foo_open0_Bar_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Foo_open0_Bar_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: Foo_open0_Bar_close0", + ][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Baz { pub _address: u8, } -#[test] -fn bindgen_test_layout_Baz() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Baz)), - ); -} -#[test] -fn __bindgen_test_layout_Foo_open0_Boo_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of template specialization: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of template specialization: ", stringify!(Foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Baz"][::std::mem::size_of::() - 1usize]; + ["Alignment of Baz"][::std::mem::align_of::() - 1usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: Foo_open0_Boo_close0", + ][::std::mem::size_of::() - 1usize]; + [ + "Align of template specialization: Foo_open0_Boo_close0", + ][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Bar { pub _address: u8, } -#[test] -fn bindgen_test_layout_Bar() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Boo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Boo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Boo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Boo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Boo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Boo"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/template_typedef_transitive_param.rs b/bindgen-tests/tests/expectations/tests/template_typedef_transitive_param.rs index 019f085c60..2efdde944e 100644 --- a/bindgen-tests/tests/expectations/tests/template_typedef_transitive_param.rs +++ b/bindgen-tests/tests/expectations/tests/template_typedef_transitive_param.rs @@ -7,8 +7,8 @@ pub struct Wrapper { #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Wrapper_Wrapped { - pub t: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub t: T, } impl Default for Wrapper_Wrapped { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/test_macro_fallback_non_system_dir.rs b/bindgen-tests/tests/expectations/tests/test_macro_fallback_non_system_dir.rs new file mode 100644 index 0000000000..bf9739f3fa --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/test_macro_fallback_non_system_dir.rs @@ -0,0 +1,6 @@ +pub const CONST: u32 = 5; +pub const OTHER_CONST: u32 = 6; +pub const LARGE_CONST: u32 = 1536; +pub const THE_CONST: u32 = 28; +pub const MY_CONST: u32 = 69; +pub const NEGATIVE: i32 = -1; diff --git a/bindgen-tests/tests/expectations/tests/test_mixed_header_and_header_contents.rs b/bindgen-tests/tests/expectations/tests/test_mixed_header_and_header_contents.rs index 5f8da2affb..e1872623bc 100644 --- a/bindgen-tests/tests/expectations/tests/test_mixed_header_and_header_contents.rs +++ b/bindgen-tests/tests/expectations/tests/test_mixed_header_and_header_contents.rs @@ -1,4 +1,4 @@ -extern "C" { +unsafe extern "C" { pub static mut foo: ::std::option::Option< unsafe extern "C" fn( x: ::std::os::raw::c_int, @@ -6,10 +6,10 @@ extern "C" { ) -> ::std::os::raw::c_int, >; } -extern "C" { +unsafe extern "C" { pub fn bar(a: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { pub fn bar2(b: *const ::std::os::raw::c_char) -> f32; } pub type Char = ::std::os::raw::c_char; @@ -31,84 +31,20 @@ pub struct Test { pub Ccu: UChar, pub Ccd: SChar, } -#[test] -fn bindgen_test_layout_Test() { - const UNINIT: ::std::mem::MaybeUninit = - ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(Test)) - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Test)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ch) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(ch)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 1usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(u)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 2usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(d)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cch) as usize - ptr as usize }, - 3usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cch)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cu) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cu)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cd) as usize - ptr as usize }, - 5usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cd)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cch) as usize - ptr as usize }, - 6usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cch)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cu) as usize - ptr as usize }, - 7usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cu)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cd) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cd)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccch) as usize - ptr as usize }, - 9usize, - concat!( - "Offset of field: ", - stringify!(Test), - "::", - stringify!(Ccch) - ) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccu) as usize - ptr as usize }, - 10usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Ccu)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccd) as usize - ptr as usize }, - 11usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Ccd)) - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 12usize]; + ["Alignment of Test"][::std::mem::align_of::() - 1usize]; + ["Offset of field: Test::ch"][::std::mem::offset_of!(Test, ch) - 0usize]; + ["Offset of field: Test::u"][::std::mem::offset_of!(Test, u) - 1usize]; + ["Offset of field: Test::d"][::std::mem::offset_of!(Test, d) - 2usize]; + ["Offset of field: Test::cch"][::std::mem::offset_of!(Test, cch) - 3usize]; + ["Offset of field: Test::cu"][::std::mem::offset_of!(Test, cu) - 4usize]; + ["Offset of field: Test::cd"][::std::mem::offset_of!(Test, cd) - 5usize]; + ["Offset of field: Test::Cch"][::std::mem::offset_of!(Test, Cch) - 6usize]; + ["Offset of field: Test::Cu"][::std::mem::offset_of!(Test, Cu) - 7usize]; + ["Offset of field: Test::Cd"][::std::mem::offset_of!(Test, Cd) - 8usize]; + ["Offset of field: Test::Ccch"][::std::mem::offset_of!(Test, Ccch) - 9usize]; + ["Offset of field: Test::Ccu"][::std::mem::offset_of!(Test, Ccu) - 10usize]; + ["Offset of field: Test::Ccd"][::std::mem::offset_of!(Test, Ccd) - 11usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/test_multiple_header_calls_in_builder.rs b/bindgen-tests/tests/expectations/tests/test_multiple_header_calls_in_builder.rs index b594d70c93..2e62ac902f 100644 --- a/bindgen-tests/tests/expectations/tests/test_multiple_header_calls_in_builder.rs +++ b/bindgen-tests/tests/expectations/tests/test_multiple_header_calls_in_builder.rs @@ -1,4 +1,4 @@ -extern "C" { +unsafe extern "C" { pub static mut foo: ::std::option::Option< unsafe extern "C" fn( x: ::std::os::raw::c_int, @@ -25,84 +25,20 @@ pub struct Test { pub Ccu: UChar, pub Ccd: SChar, } -#[test] -fn bindgen_test_layout_Test() { - const UNINIT: ::std::mem::MaybeUninit = - ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(Test)) - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Test)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ch) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(ch)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).u) as usize - ptr as usize }, - 1usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(u)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, - 2usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(d)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cch) as usize - ptr as usize }, - 3usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cch)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cu) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cu)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).cd) as usize - ptr as usize }, - 5usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(cd)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cch) as usize - ptr as usize }, - 6usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cch)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cu) as usize - ptr as usize }, - 7usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cu)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Cd) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Cd)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccch) as usize - ptr as usize }, - 9usize, - concat!( - "Offset of field: ", - stringify!(Test), - "::", - stringify!(Ccch) - ) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccu) as usize - ptr as usize }, - 10usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Ccu)) - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).Ccd) as usize - ptr as usize }, - 11usize, - concat!("Offset of field: ", stringify!(Test), "::", stringify!(Ccd)) - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 12usize]; + ["Alignment of Test"][::std::mem::align_of::() - 1usize]; + ["Offset of field: Test::ch"][::std::mem::offset_of!(Test, ch) - 0usize]; + ["Offset of field: Test::u"][::std::mem::offset_of!(Test, u) - 1usize]; + ["Offset of field: Test::d"][::std::mem::offset_of!(Test, d) - 2usize]; + ["Offset of field: Test::cch"][::std::mem::offset_of!(Test, cch) - 3usize]; + ["Offset of field: Test::cu"][::std::mem::offset_of!(Test, cu) - 4usize]; + ["Offset of field: Test::cd"][::std::mem::offset_of!(Test, cd) - 5usize]; + ["Offset of field: Test::Cch"][::std::mem::offset_of!(Test, Cch) - 6usize]; + ["Offset of field: Test::Cu"][::std::mem::offset_of!(Test, Cu) - 7usize]; + ["Offset of field: Test::Cd"][::std::mem::offset_of!(Test, Cd) - 8usize]; + ["Offset of field: Test::Ccch"][::std::mem::offset_of!(Test, Ccch) - 9usize]; + ["Offset of field: Test::Ccu"][::std::mem::offset_of!(Test, Ccu) - 10usize]; + ["Offset of field: Test::Ccd"][::std::mem::offset_of!(Test, Ccd) - 11usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/timex.rs b/bindgen-tests/tests/expectations/tests/timex.rs index 16bbae7607..3d25971315 100644 --- a/bindgen-tests/tests/expectations/tests/timex.rs +++ b/bindgen-tests/tests/expectations/tests/timex.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Debug, Copy, Clone)] @@ -90,26 +152,12 @@ pub struct timex { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 44usize]>, } -#[test] -fn bindgen_test_layout_timex() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 48usize, - concat!("Size of: ", stringify!(timex)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(timex)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tai) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(timex), "::", stringify!(tai)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of timex"][::std::mem::size_of::() - 48usize]; + ["Alignment of timex"][::std::mem::align_of::() - 4usize]; + ["Offset of field: timex::tai"][::std::mem::offset_of!(timex, tai) - 0usize]; +}; impl Default for timex { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -126,26 +174,14 @@ pub struct timex_named { pub _bitfield_align_1: [u32; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 44usize]>, } -#[test] -fn bindgen_test_layout_timex_named() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 48usize, - concat!("Size of: ", stringify!(timex_named)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(timex_named)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).tai) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(timex_named), "::", stringify!(tai)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of timex_named"][::std::mem::size_of::() - 48usize]; + ["Alignment of timex_named"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: timex_named::tai", + ][::std::mem::offset_of!(timex_named, tai) - 0usize]; +}; impl Default for timex_named { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -168,6 +204,31 @@ impl timex_named { } } #[inline] + pub unsafe fn a_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_a_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn b(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 32u8) as u32) } } @@ -179,6 +240,31 @@ impl timex_named { } } #[inline] + pub unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 32usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn c(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 32u8) as u32) } } @@ -190,6 +276,31 @@ impl timex_named { } } #[inline] + pub unsafe fn c_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 64usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_c_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn d(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(96usize, 32u8) as u32) } } @@ -201,6 +312,31 @@ impl timex_named { } } #[inline] + pub unsafe fn d_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 96usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_d_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 96usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn e(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(128usize, 32u8) as u32) } } @@ -212,6 +348,31 @@ impl timex_named { } } #[inline] + pub unsafe fn e_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 128usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_e_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 128usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn f(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(160usize, 32u8) as u32) } } @@ -223,6 +384,31 @@ impl timex_named { } } #[inline] + pub unsafe fn f_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 160usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_f_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 160usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn g(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(192usize, 32u8) as u32) } } @@ -234,6 +420,31 @@ impl timex_named { } } #[inline] + pub unsafe fn g_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 192usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_g_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 192usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn h(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(224usize, 32u8) as u32) } } @@ -245,6 +456,31 @@ impl timex_named { } } #[inline] + pub unsafe fn h_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 224usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_h_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 224usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn i(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(256usize, 32u8) as u32) } } @@ -256,6 +492,31 @@ impl timex_named { } } #[inline] + pub unsafe fn i_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 256usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_i_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 256usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn j(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(288usize, 32u8) as u32) } } @@ -267,6 +528,31 @@ impl timex_named { } } #[inline] + pub unsafe fn j_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 288usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_j_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 288usize, + 32u8, + val as u64, + ) + } + } + #[inline] pub fn k(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(320usize, 32u8) as u32) } } @@ -277,4 +563,29 @@ impl timex_named { self._bitfield_1.set(320usize, 32u8, val as u64) } } + #[inline] + pub unsafe fn k_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 320usize, 32u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_k_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 44usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 320usize, + 32u8, + val as u64, + ) + } + } } diff --git a/bindgen-tests/tests/expectations/tests/transform-op.rs b/bindgen-tests/tests/expectations/tests/transform-op.rs index 85c34985c3..c626049b46 100644 --- a/bindgen-tests/tests/expectations/tests/transform-op.rs +++ b/bindgen-tests/tests/expectations/tests/transform-op.rs @@ -3,7 +3,7 @@ pub struct __BindgenUnionField(::std::marker::PhantomData); impl __BindgenUnionField { #[inline] - pub fn new() -> Self { + pub const fn new() -> Self { __BindgenUnionField(::std::marker::PhantomData) } #[inline] @@ -45,9 +45,9 @@ impl ::std::cmp::Eq for __BindgenUnionField {} #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct StylePoint { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub x: T, pub y: T, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for StylePoint { fn default() -> Self { @@ -59,14 +59,14 @@ impl Default for StylePoint { } } #[repr(C)] -#[derive(Debug, Default, Copy, Clone)] +#[repr(align(1))] pub struct StyleFoo { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub __bindgen_anon_1: __BindgenUnionField, pub foo: __BindgenUnionField>, pub bar: __BindgenUnionField>, pub baz: __BindgenUnionField>, pub bindgen_union_field: [u8; 0usize], - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } pub const StyleFoo_Tag_Foo: StyleFoo_Tag = 0; pub const StyleFoo_Tag_Bar: StyleFoo_Tag = 0; @@ -76,11 +76,11 @@ pub type StyleFoo_Tag = u8; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct StyleFoo_Foo_Body { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub tag: StyleFoo_Tag, pub x: i32, pub y: StylePoint, pub z: StylePoint, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for StyleFoo_Foo_Body { fn default() -> Self { @@ -94,9 +94,9 @@ impl Default for StyleFoo_Foo_Body { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct StyleFoo_Bar_Body { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub tag: StyleFoo_Tag, pub _0: T, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for StyleFoo_Bar_Body { fn default() -> Self { @@ -110,9 +110,9 @@ impl Default for StyleFoo_Bar_Body { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct StyleFoo_Baz_Body { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub tag: StyleFoo_Tag, pub _0: StylePoint, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for StyleFoo_Baz_Body { fn default() -> Self { @@ -137,12 +137,20 @@ impl Default for StyleFoo__bindgen_ty_1 { } } } +impl Default for StyleFoo { + fn default() -> Self { + unsafe { + let mut s: Self = ::std::mem::uninitialized(); + ::std::ptr::write_bytes(&mut s, 0, 1); + s + } + } +} #[repr(C)] -#[derive(Debug, Copy, Clone)] pub struct StyleBar { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub tag: StyleBar_Tag, pub __bindgen_anon_1: StyleBar__bindgen_ty_1, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } pub const StyleBar_Tag_Bar1: StyleBar_Tag = 0; pub const StyleBar_Tag_Bar2: StyleBar_Tag = 0; @@ -152,10 +160,10 @@ pub type StyleBar_Tag = ::std::os::raw::c_int; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct StyleBar_StyleBar1_Body { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub x: i32, pub y: StylePoint, pub z: StylePoint, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for StyleBar_StyleBar1_Body { fn default() -> Self { @@ -169,8 +177,8 @@ impl Default for StyleBar_StyleBar1_Body { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct StyleBar_StyleBar2_Body { - pub _0: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub _0: T, } impl Default for StyleBar_StyleBar2_Body { fn default() -> Self { @@ -184,8 +192,8 @@ impl Default for StyleBar_StyleBar2_Body { #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct StyleBar_StyleBar3_Body { - pub _0: StylePoint, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub _0: StylePoint, } impl Default for StyleBar_StyleBar3_Body { fn default() -> Self { @@ -197,13 +205,22 @@ impl Default for StyleBar_StyleBar3_Body { } } #[repr(C)] -#[derive(Debug, Default, Copy, Clone)] +#[repr(align(1))] pub struct StyleBar__bindgen_ty_1 { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub bar1: __BindgenUnionField>, pub bar2: __BindgenUnionField>, pub bar3: __BindgenUnionField>, pub bindgen_union_field: [u8; 0usize], - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, +} +impl Default for StyleBar__bindgen_ty_1 { + fn default() -> Self { + unsafe { + let mut s: Self = ::std::mem::uninitialized(); + ::std::ptr::write_bytes(&mut s, 0, 1); + s + } + } } impl Default for StyleBar { fn default() -> Self { @@ -219,12 +236,12 @@ fn __bindgen_test_layout_StylePoint_open0_float_close0_instantiation() { assert_eq!( ::std::mem::size_of::>(), 8usize, - concat!("Size of template specialization: ", stringify!(StylePoint < f32 >)), + "Size of template specialization: StylePoint_open0_float_close0", ); assert_eq!( ::std::mem::align_of::>(), 4usize, - concat!("Alignment of template specialization: ", stringify!(StylePoint < f32 >)), + "Align of template specialization: StylePoint_open0_float_close0", ); } #[test] @@ -232,11 +249,11 @@ fn __bindgen_test_layout_StylePoint_open0_float_close0_instantiation_1() { assert_eq!( ::std::mem::size_of::>(), 8usize, - concat!("Size of template specialization: ", stringify!(StylePoint < f32 >)), + "Size of template specialization: StylePoint_open0_float_close0", ); assert_eq!( ::std::mem::align_of::>(), 4usize, - concat!("Alignment of template specialization: ", stringify!(StylePoint < f32 >)), + "Align of template specialization: StylePoint_open0_float_close0", ); } diff --git a/bindgen-tests/tests/expectations/tests/type-referenced-by-allowlisted-function.rs b/bindgen-tests/tests/expectations/tests/type-referenced-by-allowlisted-function.rs index 62ebce73fb..6d1c43d9cc 100644 --- a/bindgen-tests/tests/expectations/tests/type-referenced-by-allowlisted-function.rs +++ b/bindgen-tests/tests/expectations/tests/type-referenced-by-allowlisted-function.rs @@ -4,26 +4,14 @@ pub struct dl_phdr_info { pub x: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_dl_phdr_info() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(dl_phdr_info)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(dl_phdr_info)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(dl_phdr_info), "::", stringify!(x)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of dl_phdr_info"][::std::mem::size_of::() - 4usize]; + ["Alignment of dl_phdr_info"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: dl_phdr_info::x", + ][::std::mem::offset_of!(dl_phdr_info, x) - 0usize]; +}; +unsafe extern "C" { pub fn dl_iterate_phdr(arg1: *mut dl_phdr_info) -> ::std::os::raw::c_int; } diff --git a/bindgen-tests/tests/expectations/tests/type_alias_partial_template_especialization.rs b/bindgen-tests/tests/expectations/tests/type_alias_partial_template_especialization.rs index 48c388d6f9..29df017a9b 100644 --- a/bindgen-tests/tests/expectations/tests/type_alias_partial_template_especialization.rs +++ b/bindgen-tests/tests/expectations/tests/type_alias_partial_template_especialization.rs @@ -3,8 +3,8 @@ pub type MaybeWrapped
= A; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Rooted { - pub ptr: MaybeWrapped, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, + pub ptr: MaybeWrapped, } impl Default for Rooted { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/type_alias_template_specialized.rs b/bindgen-tests/tests/expectations/tests/type_alias_template_specialized.rs index d585a857d9..13e3f8139c 100644 --- a/bindgen-tests/tests/expectations/tests/type_alias_template_specialized.rs +++ b/bindgen-tests/tests/expectations/tests/type_alias_template_specialized.rs @@ -4,26 +4,12 @@ pub struct Rooted { pub ptr: MaybeWrapped<::std::os::raw::c_int>, } -#[test] -fn bindgen_test_layout_Rooted() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Rooted)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Rooted)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).ptr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Rooted), "::", stringify!(ptr)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Rooted"][::std::mem::size_of::() - 4usize]; + ["Alignment of Rooted"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Rooted::ptr"][::std::mem::offset_of!(Rooted, ptr) - 0usize]; +}; impl Default for Rooted { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -35,22 +21,12 @@ impl Default for Rooted { } ///
pub type MaybeWrapped
= a; -#[test] -fn __bindgen_test_layout_MaybeWrapped_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::>(), - 4usize, - concat!( - "Size of template specialization: ", - stringify!(MaybeWrapped < ::std::os::raw::c_int >), - ), - ); - assert_eq!( - ::std::mem::align_of::>(), - 4usize, - concat!( - "Alignment of template specialization: ", - stringify!(MaybeWrapped < ::std::os::raw::c_int >), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: MaybeWrapped_open0_int_close0", + ][::std::mem::size_of::>() - 4usize]; + [ + "Align of template specialization: MaybeWrapped_open0_int_close0", + ][::std::mem::align_of::>() - 4usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/typedef-pointer-overlap.rs b/bindgen-tests/tests/expectations/tests/typedef-pointer-overlap.rs index 3e04de9185..122059b4e1 100644 --- a/bindgen-tests/tests/expectations/tests/typedef-pointer-overlap.rs +++ b/bindgen-tests/tests/expectations/tests/typedef-pointer-overlap.rs @@ -4,52 +4,24 @@ pub struct foo { pub inner: ::std::os::raw::c_char, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).inner) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(inner)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of foo"][::std::mem::align_of::() - 1usize]; + ["Offset of field: foo::inner"][::std::mem::offset_of!(foo, inner) - 0usize]; +}; pub type foo_ptr = *const foo; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct bar { pub inner: ::std::os::raw::c_char, } -#[test] -fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).inner) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(inner)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of bar"][::std::mem::align_of::() - 1usize]; + ["Offset of field: bar::inner"][::std::mem::offset_of!(bar, inner) - 0usize]; +}; pub type bar_ptr = *mut bar; #[repr(C)] #[derive(Debug, Copy, Clone)] @@ -62,26 +34,14 @@ pub type baz_ptr = *mut baz; pub union cat { pub standard_issue: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_cat() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(cat)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(cat)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).standard_issue) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(cat), "::", stringify!(standard_issue)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of cat"][::std::mem::size_of::() - 4usize]; + ["Alignment of cat"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: cat::standard_issue", + ][::std::mem::offset_of!(cat, standard_issue) - 0usize]; +}; impl Default for cat { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -95,33 +55,33 @@ pub type cat_ptr = *mut cat; pub const mad_scientist: mad = 0; pub type mad = ::std::os::raw::c_uint; pub type mad_ptr = *mut mad; -extern "C" { +unsafe extern "C" { pub fn takes_foo_ptr(arg1: foo_ptr); } -extern "C" { +unsafe extern "C" { pub fn takes_foo_struct(arg1: foo); } -extern "C" { +unsafe extern "C" { pub fn takes_bar_ptr(arg1: bar_ptr); } -extern "C" { +unsafe extern "C" { pub fn takes_bar_struct(arg1: bar); } -extern "C" { +unsafe extern "C" { pub fn takes_baz_ptr(arg1: baz_ptr); } -extern "C" { +unsafe extern "C" { pub fn takes_baz_struct(arg1: baz); } -extern "C" { +unsafe extern "C" { pub fn takes_cat_ptr(arg1: cat_ptr); } -extern "C" { +unsafe extern "C" { pub fn takes_cat_union(arg1: cat); } -extern "C" { +unsafe extern "C" { pub fn takes_mad_ptr(arg1: mad_ptr); } -extern "C" { +unsafe extern "C" { pub fn takes_mad_enum(arg1: mad); } diff --git a/bindgen-tests/tests/expectations/tests/typedefd-array-as-function-arg.rs b/bindgen-tests/tests/expectations/tests/typedefd-array-as-function-arg.rs index 792b243a7a..994b327da7 100644 --- a/bindgen-tests/tests/expectations/tests/typedefd-array-as-function-arg.rs +++ b/bindgen-tests/tests/expectations/tests/typedefd-array-as-function-arg.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] pub type myVector3 = [f32; 3usize]; -extern "C" { +unsafe extern "C" { pub fn modifyVectorFunc(v: *mut f32); } diff --git a/bindgen-tests/tests/expectations/tests/typeref.rs b/bindgen-tests/tests/expectations/tests/typeref.rs index 31f9d2c697..e48f0eb254 100644 --- a/bindgen-tests/tests/expectations/tests/typeref.rs +++ b/bindgen-tests/tests/expectations/tests/typeref.rs @@ -4,49 +4,30 @@ pub struct mozilla_FragmentOrURL { pub mIsLocalRef: bool, } -#[test] -fn bindgen_test_layout_mozilla_FragmentOrURL() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(mozilla_FragmentOrURL)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(mozilla_FragmentOrURL)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mIsLocalRef) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(mozilla_FragmentOrURL), - "::", - stringify!(mIsLocalRef), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of mozilla_FragmentOrURL", + ][::std::mem::size_of::() - 1usize]; + [ + "Alignment of mozilla_FragmentOrURL", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: mozilla_FragmentOrURL::mIsLocalRef", + ][::std::mem::offset_of!(mozilla_FragmentOrURL, mIsLocalRef) - 0usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct mozilla_Position { pub _address: u8, } -#[test] -fn bindgen_test_layout_mozilla_Position() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(mozilla_Position)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(mozilla_Position)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of mozilla_Position"][::std::mem::size_of::() - 1usize]; + [ + "Alignment of mozilla_Position", + ][::std::mem::align_of::() - 1usize]; +}; #[repr(C)] pub struct mozilla_StyleShapeSource { pub __bindgen_anon_1: mozilla_StyleShapeSource__bindgen_ty_1, @@ -79,26 +60,12 @@ impl Default for mozilla_StyleShapeSource { pub struct Bar { pub mFoo: *mut nsFoo, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFoo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(mFoo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 8usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 8usize]; + ["Offset of field: Bar::mFoo"][::std::mem::offset_of!(Bar, mFoo) - 0usize]; +}; impl Default for Bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -112,26 +79,12 @@ impl Default for Bar { pub struct nsFoo { pub mBar: mozilla_StyleShapeSource, } -#[test] -fn bindgen_test_layout_nsFoo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsFoo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsFoo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsFoo), "::", stringify!(mBar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of nsFoo"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsFoo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: nsFoo::mBar"][::std::mem::offset_of!(nsFoo, mBar) - 0usize]; +}; impl Default for nsFoo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -141,22 +94,12 @@ impl Default for nsFoo { } } } -#[test] -fn __bindgen_test_layout_mozilla_StyleShapeSource_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(mozilla_StyleShapeSource), - ), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(mozilla_StyleShapeSource), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of template specialization: mozilla_StyleShapeSource_open0_int_close0", + ][::std::mem::size_of::() - 8usize]; + [ + "Align of template specialization: mozilla_StyleShapeSource_open0_int_close0", + ][::std::mem::align_of::() - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/typeref_1_0.rs b/bindgen-tests/tests/expectations/tests/typeref_1_0.rs deleted file mode 100644 index 16bb52c19c..0000000000 --- a/bindgen-tests/tests/expectations/tests/typeref_1_0.rs +++ /dev/null @@ -1,202 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct mozilla_FragmentOrURL { - pub mIsLocalRef: bool, -} -#[test] -fn bindgen_test_layout_mozilla_FragmentOrURL() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(mozilla_FragmentOrURL)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(mozilla_FragmentOrURL)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mIsLocalRef) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(mozilla_FragmentOrURL), - "::", - stringify!(mIsLocalRef), - ), - ); -} -impl Clone for mozilla_FragmentOrURL { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct mozilla_Position { - pub _address: u8, -} -#[test] -fn bindgen_test_layout_mozilla_Position() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(mozilla_Position)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(mozilla_Position)), - ); -} -impl Clone for mozilla_Position { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct mozilla_StyleShapeSource { - pub __bindgen_anon_1: mozilla_StyleShapeSource__bindgen_ty_1, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct mozilla_StyleShapeSource__bindgen_ty_1 { - pub mPosition: __BindgenUnionField<*mut mozilla_Position>, - pub mFragmentOrURL: __BindgenUnionField<*mut mozilla_FragmentOrURL>, - pub bindgen_union_field: u64, -} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct Bar { - pub mFoo: *mut nsFoo, -} -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFoo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(mFoo)), - ); -} -impl Clone for Bar { - fn clone(&self) -> Self { - *self - } -} -impl Default for Bar { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct nsFoo { - pub mBar: mozilla_StyleShapeSource, -} -#[test] -fn bindgen_test_layout_nsFoo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsFoo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsFoo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsFoo), "::", stringify!(mBar)), - ); -} -impl Clone for nsFoo { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn __bindgen_test_layout_mozilla_StyleShapeSource_open0_int_close0_instantiation() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!( - "Size of template specialization: ", - stringify!(mozilla_StyleShapeSource), - ), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!( - "Alignment of template specialization: ", - stringify!(mozilla_StyleShapeSource), - ), - ); -} diff --git a/bindgen-tests/tests/expectations/tests/uncallable_functions.rs b/bindgen-tests/tests/expectations/tests/uncallable_functions.rs new file mode 100644 index 0000000000..fddb5d41fc --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/uncallable_functions.rs @@ -0,0 +1,46 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +pub struct Test__bindgen_vtable { + pub Test_a: unsafe extern "C" fn(this: *mut Test), +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct Test { + pub vtable_: *const Test__bindgen_vtable, +} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Test"][::std::mem::size_of::() - 8usize]; + ["Alignment of Test"][::std::mem::align_of::() - 8usize]; +}; +unsafe extern "C" { + #[link_name = "\u{1}_ZN4Test1bEv"] + pub fn Test_b(this: *mut Test); +} +unsafe extern "C" { + #[link_name = "\u{1}_ZN4Test1cEv"] + pub fn Test_c(this: *mut Test); +} +impl Default for Test { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Test { + #[inline] + pub unsafe fn b(&mut self) { + Test_b(self) + } + #[inline] + pub unsafe fn c(&mut self) { + Test_c(self) + } +} +unsafe extern "C" { + #[link_name = "\u{1}_ZN4Test1aEv"] + pub fn Test_a(this: *mut ::std::os::raw::c_void); +} diff --git a/bindgen-tests/tests/expectations/tests/underscore.rs b/bindgen-tests/tests/expectations/tests/underscore.rs index 59897e41fd..f94d5fc580 100644 --- a/bindgen-tests/tests/expectations/tests/underscore.rs +++ b/bindgen-tests/tests/expectations/tests/underscore.rs @@ -5,23 +5,9 @@ pub const __: ::std::os::raw::c_int = 10; pub struct ptr_t { pub __: [::std::os::raw::c_uchar; 8usize], } -#[test] -fn bindgen_test_layout_ptr_t() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(ptr_t)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ptr_t)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).__) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(ptr_t), "::", stringify!(__)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ptr_t"][::std::mem::size_of::() - 8usize]; + ["Alignment of ptr_t"][::std::mem::align_of::() - 1usize]; + ["Offset of field: ptr_t::__"][::std::mem::offset_of!(ptr_t, __) - 0usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/union-align.rs b/bindgen-tests/tests/expectations/tests/union-align.rs index 0047834f81..2838ef34c3 100644 --- a/bindgen-tests/tests/expectations/tests/union-align.rs +++ b/bindgen-tests/tests/expectations/tests/union-align.rs @@ -9,20 +9,12 @@ pub union Bar { fn bindgen_test_layout_Bar() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(Bar)), - ); + assert_eq!(::std::mem::size_of::(), 16usize, "Size of Bar"); + assert_eq!(::std::mem::align_of::(), 16usize, "Alignment of Bar"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(foo)), + "Offset of field: Bar::foo", ); } impl Default for Bar { @@ -44,20 +36,12 @@ pub union Baz { fn bindgen_test_layout_Baz() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(Baz)), - ); + assert_eq!(::std::mem::size_of::(), 16usize, "Size of Baz"); + assert_eq!(::std::mem::align_of::(), 16usize, "Alignment of Baz"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(Baz), "::", stringify!(bar)), + "Offset of field: Baz::bar", ); } impl Default for Baz { diff --git a/bindgen-tests/tests/expectations/tests/union-in-ns.rs b/bindgen-tests/tests/expectations/tests/union-in-ns.rs index 58160c65a9..781041addb 100644 --- a/bindgen-tests/tests/expectations/tests/union-in-ns.rs +++ b/bindgen-tests/tests/expectations/tests/union-in-ns.rs @@ -8,26 +8,12 @@ pub mod root { pub union bar { pub baz: ::std::os::raw::c_int, } - #[test] - fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(baz)), - ); - } + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + ["Size of bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: bar::baz"][::std::mem::offset_of!(bar, baz) - 0usize]; + }; impl Default for bar { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union-in-ns_1_0.rs b/bindgen-tests/tests/expectations/tests/union-in-ns_1_0.rs deleted file mode 100644 index f80cff753b..0000000000 --- a/bindgen-tests/tests/expectations/tests/union-in-ns_1_0.rs +++ /dev/null @@ -1,80 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] -pub mod root { - #[repr(C)] - pub struct __BindgenUnionField(::std::marker::PhantomData); - impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } - } - impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } - } - impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } - } - impl ::std::marker::Copy for __BindgenUnionField {} - impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } - } - impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} - } - impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } - } - impl ::std::cmp::Eq for __BindgenUnionField {} - #[allow(unused_imports)] - use self::super::root; - #[repr(C)] - #[derive(Debug, Default, Copy)] - pub struct bar { - pub baz: root::__BindgenUnionField<::std::os::raw::c_int>, - pub bindgen_union_field: u32, - } - #[test] - fn bindgen_test_layout_bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(bar), "::", stringify!(baz)), - ); - } - impl Clone for bar { - fn clone(&self) -> Self { - *self - } - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_bitfield.rs b/bindgen-tests/tests/expectations/tests/union_bitfield.rs index 7f4bd37f35..70da5c3b02 100644 --- a/bindgen-tests/tests/expectations/tests/union_bitfield.rs +++ b/bindgen-tests/tests/expectations/tests/union_bitfield.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[repr(align(4))] @@ -90,19 +152,11 @@ pub union U4 { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, } -#[test] -fn bindgen_test_layout_U4() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(U4)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(U4)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of U4"][::std::mem::size_of::() - 4usize]; + ["Alignment of U4"][::std::mem::align_of::() - 4usize]; +}; impl Default for U4 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -125,6 +179,31 @@ impl U4 { } } #[inline] + pub unsafe fn derp_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 1u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_derp_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 1usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( derp: ::std::os::raw::c_uint, ) -> __BindgenBitfieldUnit<[u8; 1usize]> { @@ -147,15 +226,11 @@ pub union B { pub _bitfield_align_1: [u32; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, } -#[test] -fn bindgen_test_layout_B() { - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(B)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of B"][::std::mem::size_of::() - 4usize]; + ["Alignment of B"][::std::mem::align_of::() - 4usize]; +}; impl Default for B { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -178,6 +253,31 @@ impl B { } } #[inline] + pub unsafe fn foo_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 31u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_foo_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 31u8, + val as u64, + ) + } + } + #[inline] pub fn bar(&self) -> ::std::os::raw::c_uchar { unsafe { ::std::mem::transmute(self._bitfield_1.get(31usize, 1u8) as u8) } } @@ -189,6 +289,31 @@ impl B { } } #[inline] + pub unsafe fn bar_raw(this: *const Self) -> ::std::os::raw::c_uchar { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 31usize, 1u8) + as u8, + ) + } + } + #[inline] + pub unsafe fn set_bar_raw(this: *mut Self, val: ::std::os::raw::c_uchar) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 31usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( foo: ::std::os::raw::c_uint, bar: ::std::os::raw::c_uchar, diff --git a/bindgen-tests/tests/expectations/tests/union_bitfield_1_0.rs b/bindgen-tests/tests/expectations/tests/union_bitfield_1_0.rs deleted file mode 100644 index e3b65e5011..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_bitfield_1_0.rs +++ /dev/null @@ -1,293 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub struct __BindgenBitfieldUnit { - storage: Storage, -} -impl __BindgenBitfieldUnit { - #[inline] - pub fn new(storage: Storage) -> Self { - Self { storage } - } -} -impl __BindgenBitfieldUnit -where - Storage: AsRef<[u8]> + AsMut<[u8]>, -{ - #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - byte & mask == mask - } - #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } - } - #[inline] - pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - let mut val = 0; - for i in 0..(bit_width as usize) { - if self.get_bit(i + bit_offset) { - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - val |= 1 << index; - } - } - val - } - #[inline] - pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - for i in 0..(bit_width as usize) { - let mask = 1 << i; - let val_bit_is_set = val & mask == mask; - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - self.set_bit(index + bit_offset, val_bit_is_set); - } - } -} -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct U4 { - pub _bitfield_align_1: [u8; 0], - pub _bitfield_1: __BindgenUnionField<__BindgenBitfieldUnit<[u8; 1usize]>>, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_U4() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(U4)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(U4)), - ); -} -impl Clone for U4 { - fn clone(&self) -> Self { - *self - } -} -impl U4 { - #[inline] - pub fn derp(&self) -> ::std::os::raw::c_uint { - unsafe { - ::std::mem::transmute(self._bitfield_1.as_ref().get(0usize, 1u8) as u32) - } - } - #[inline] - pub fn set_derp(&mut self, val: ::std::os::raw::c_uint) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.as_mut().set(0usize, 1u8, val as u64) - } - } - #[inline] - pub fn new_bitfield_1( - derp: ::std::os::raw::c_uint, - ) -> __BindgenBitfieldUnit<[u8; 1usize]> { - let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); - __bindgen_bitfield_unit - .set( - 0usize, - 1u8, - { - let derp: u32 = unsafe { ::std::mem::transmute(derp) }; - derp as u64 - }, - ); - __bindgen_bitfield_unit - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct B { - pub _bitfield_align_1: [u32; 0], - pub _bitfield_1: __BindgenUnionField<__BindgenBitfieldUnit<[u8; 4usize]>>, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_B() { - assert_eq!(::std::mem::size_of::(), 4usize, concat!("Size of: ", stringify!(B))); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(B)), - ); -} -impl Clone for B { - fn clone(&self) -> Self { - *self - } -} -impl B { - #[inline] - pub fn foo(&self) -> ::std::os::raw::c_uint { - unsafe { - ::std::mem::transmute(self._bitfield_1.as_ref().get(0usize, 31u8) as u32) - } - } - #[inline] - pub fn set_foo(&mut self, val: ::std::os::raw::c_uint) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.as_mut().set(0usize, 31u8, val as u64) - } - } - #[inline] - pub fn bar(&self) -> ::std::os::raw::c_uchar { - unsafe { - ::std::mem::transmute(self._bitfield_1.as_ref().get(31usize, 1u8) as u8) - } - } - #[inline] - pub fn set_bar(&mut self, val: ::std::os::raw::c_uchar) { - unsafe { - let val: u8 = ::std::mem::transmute(val); - self._bitfield_1.as_mut().set(31usize, 1u8, val as u64) - } - } - #[inline] - pub fn new_bitfield_1( - foo: ::std::os::raw::c_uint, - bar: ::std::os::raw::c_uchar, - ) -> __BindgenBitfieldUnit<[u8; 4usize]> { - let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); - __bindgen_bitfield_unit - .set( - 0usize, - 31u8, - { - let foo: u32 = unsafe { ::std::mem::transmute(foo) }; - foo as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 31usize, - 1u8, - { - let bar: u8 = unsafe { ::std::mem::transmute(bar) }; - bar as u64 - }, - ); - __bindgen_bitfield_unit - } -} -#[repr(C)] -#[derive(Copy)] -pub struct HasBigBitfield { - pub _bitfield_align_1: [u64; 0], - pub _bitfield_1: __BindgenUnionField<__BindgenBitfieldUnit<[u8; 16usize]>>, - pub bindgen_union_field: [u8; 16usize], -} -#[test] -fn bindgen_test_layout_HasBigBitfield() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(HasBigBitfield)), - ); -} -impl Clone for HasBigBitfield { - fn clone(&self) -> Self { - *self - } -} -impl Default for HasBigBitfield { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -impl ::std::cmp::PartialEq for HasBigBitfield { - fn eq(&self, other: &HasBigBitfield) -> bool { - &self.bindgen_union_field[..] == &other.bindgen_union_field[..] - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_dtor.rs b/bindgen-tests/tests/expectations/tests/union_dtor.rs index 5eea0cacda..3b89587098 100644 --- a/bindgen-tests/tests/expectations/tests/union_dtor.rs +++ b/bindgen-tests/tests/expectations/tests/union_dtor.rs @@ -4,32 +4,18 @@ pub union UnionWithDtor { pub mFoo: ::std::os::raw::c_int, pub mBar: *mut ::std::os::raw::c_void, } -#[test] -fn bindgen_test_layout_UnionWithDtor() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(UnionWithDtor)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(UnionWithDtor)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFoo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(UnionWithDtor), "::", stringify!(mFoo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(UnionWithDtor), "::", stringify!(mBar)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of UnionWithDtor"][::std::mem::size_of::() - 8usize]; + ["Alignment of UnionWithDtor"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: UnionWithDtor::mFoo", + ][::std::mem::offset_of!(UnionWithDtor, mFoo) - 0usize]; + [ + "Offset of field: UnionWithDtor::mBar", + ][::std::mem::offset_of!(UnionWithDtor, mBar) - 0usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN13UnionWithDtorD1Ev"] pub fn UnionWithDtor_UnionWithDtor_destructor(this: *mut UnionWithDtor); } diff --git a/bindgen-tests/tests/expectations/tests/union_dtor_1_0.rs b/bindgen-tests/tests/expectations/tests/union_dtor_1_0.rs deleted file mode 100644 index a37109ab08..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_dtor_1_0.rs +++ /dev/null @@ -1,86 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default)] -pub struct UnionWithDtor { - pub mFoo: __BindgenUnionField<::std::os::raw::c_int>, - pub mBar: __BindgenUnionField<*mut ::std::os::raw::c_void>, - pub bindgen_union_field: u64, -} -#[test] -fn bindgen_test_layout_UnionWithDtor() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(UnionWithDtor)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(UnionWithDtor)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFoo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(UnionWithDtor), "::", stringify!(mFoo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mBar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(UnionWithDtor), "::", stringify!(mBar)), - ); -} -extern "C" { - #[link_name = "\u{1}_ZN13UnionWithDtorD1Ev"] - pub fn UnionWithDtor_UnionWithDtor_destructor(this: *mut UnionWithDtor); -} -impl UnionWithDtor { - #[inline] - pub unsafe fn destruct(&mut self) { - UnionWithDtor_UnionWithDtor_destructor(self) - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_fields.rs b/bindgen-tests/tests/expectations/tests/union_fields.rs index 30f130c3c1..c3d0f8db61 100644 --- a/bindgen-tests/tests/expectations/tests/union_fields.rs +++ b/bindgen-tests/tests/expectations/tests/union_fields.rs @@ -6,41 +6,20 @@ pub union nsStyleUnion { pub mFloat: f32, pub mPointer: *mut ::std::os::raw::c_void, } -#[test] -fn bindgen_test_layout_nsStyleUnion() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsStyleUnion)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsStyleUnion)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mInt) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mInt)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFloat) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mFloat)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mPointer) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(nsStyleUnion), - "::", - stringify!(mPointer), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of nsStyleUnion"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsStyleUnion"][::std::mem::align_of::() - 8usize]; + [ + "Offset of field: nsStyleUnion::mInt", + ][::std::mem::offset_of!(nsStyleUnion, mInt) - 0usize]; + [ + "Offset of field: nsStyleUnion::mFloat", + ][::std::mem::offset_of!(nsStyleUnion, mFloat) - 0usize]; + [ + "Offset of field: nsStyleUnion::mPointer", + ][::std::mem::offset_of!(nsStyleUnion, mPointer) - 0usize]; +}; impl Default for nsStyleUnion { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_fields_1_0.rs b/bindgen-tests/tests/expectations/tests/union_fields_1_0.rs deleted file mode 100644 index 8fbade8c25..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_fields_1_0.rs +++ /dev/null @@ -1,92 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq)] -pub struct nsStyleUnion { - pub mInt: __BindgenUnionField<::std::os::raw::c_int>, - pub mFloat: __BindgenUnionField, - pub mPointer: __BindgenUnionField<*mut ::std::os::raw::c_void>, - pub bindgen_union_field: u64, -} -#[test] -fn bindgen_test_layout_nsStyleUnion() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsStyleUnion)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsStyleUnion)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mInt) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mInt)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFloat) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mFloat)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mPointer) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(nsStyleUnion), - "::", - stringify!(mPointer), - ), - ); -} -impl Clone for nsStyleUnion { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_struct.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_struct.rs index 16f04b383e..20f4dd2265 100644 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_struct.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_anon_struct.rs @@ -10,51 +10,25 @@ pub struct foo__bindgen_ty_1 { pub a: ::std::os::raw::c_uint, pub b: ::std::os::raw::c_uint, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 4usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_struct_1_0.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_struct_1_0.rs deleted file mode 100644 index 4bc131bd3d..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_struct_1_0.rs +++ /dev/null @@ -1,111 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub bar: __BindgenUnionField, - pub bindgen_union_field: [u32; 2usize], -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1 { - pub a: ::std::os::raw::c_uint, - pub b: ::std::os::raw::c_uint, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -impl Clone for foo__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_struct_bitfield.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_struct_bitfield.rs index 48a1bda9dc..dd1a55e9b5 100644 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_struct_bitfield.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_anon_struct_bitfield.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(C)] #[derive(Copy, Clone)] @@ -95,19 +157,13 @@ pub struct foo__bindgen_ty_1 { pub _bitfield_align_1: [u32; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; +}; impl foo__bindgen_ty_1 { #[inline] pub fn b(&self) -> ::std::os::raw::c_int { @@ -121,6 +177,31 @@ impl foo__bindgen_ty_1 { } } #[inline] + pub unsafe fn b_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 7u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_b_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 7u8, + val as u64, + ) + } + } + #[inline] pub fn c(&self) -> ::std::os::raw::c_int { unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 25u8) as u32) } } @@ -132,6 +213,31 @@ impl foo__bindgen_ty_1 { } } #[inline] + pub unsafe fn c_raw(this: *const Self) -> ::std::os::raw::c_int { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 7usize, 25u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_c_raw(this: *mut Self, val: ::std::os::raw::c_int) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 25u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( b: ::std::os::raw::c_int, c: ::std::os::raw::c_int, @@ -158,26 +264,12 @@ impl foo__bindgen_ty_1 { __bindgen_bitfield_unit } } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::a"][::std::mem::offset_of!(foo, a) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_struct_bitfield_1_0.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_struct_bitfield_1_0.rs deleted file mode 100644 index 530cb7ea6a..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_struct_bitfield_1_0.rs +++ /dev/null @@ -1,234 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub struct __BindgenBitfieldUnit { - storage: Storage, -} -impl __BindgenBitfieldUnit { - #[inline] - pub fn new(storage: Storage) -> Self { - Self { storage } - } -} -impl __BindgenBitfieldUnit -where - Storage: AsRef<[u8]> + AsMut<[u8]>, -{ - #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - byte & mask == mask - } - #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; - let bit_index = if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; - let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } - } - #[inline] - pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - let mut val = 0; - for i in 0..(bit_width as usize) { - if self.get_bit(i + bit_offset) { - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - val |= 1 << index; - } - } - val - } - #[inline] - pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { - debug_assert!(bit_width <= 64); - debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!( - (bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len(), - ); - for i in 0..(bit_width as usize) { - let mask = 1 << i; - let val_bit_is_set = val & mask == mask; - let index = if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; - self.set_bit(index + bit_offset, val_bit_is_set); - } - } -} -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub a: __BindgenUnionField<::std::os::raw::c_int>, - pub __bindgen_anon_1: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1 { - pub _bitfield_align_1: [u32; 0], - pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); -} -impl Clone for foo__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -impl foo__bindgen_ty_1 { - #[inline] - pub fn b(&self) -> ::std::os::raw::c_int { - unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 7u8) as u32) } - } - #[inline] - pub fn set_b(&mut self, val: ::std::os::raw::c_int) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(0usize, 7u8, val as u64) - } - } - #[inline] - pub fn c(&self) -> ::std::os::raw::c_int { - unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 25u8) as u32) } - } - #[inline] - pub fn set_c(&mut self, val: ::std::os::raw::c_int) { - unsafe { - let val: u32 = ::std::mem::transmute(val); - self._bitfield_1.set(7usize, 25u8, val as u64) - } - } - #[inline] - pub fn new_bitfield_1( - b: ::std::os::raw::c_int, - c: ::std::os::raw::c_int, - ) -> __BindgenBitfieldUnit<[u8; 4usize]> { - let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); - __bindgen_bitfield_unit - .set( - 0usize, - 7u8, - { - let b: u32 = unsafe { ::std::mem::transmute(b) }; - b as u64 - }, - ); - __bindgen_bitfield_unit - .set( - 7usize, - 25u8, - { - let c: u32 = unsafe { ::std::mem::transmute(c) }; - c as u64 - }, - ); - __bindgen_bitfield_unit - } -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_union.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_union.rs index cbdeca49c0..212a159cd2 100644 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_union.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_anon_union.rs @@ -10,31 +10,19 @@ pub union foo__bindgen_ty_1 { pub a: ::std::os::raw::c_uint, pub b: ::std::os::raw::c_ushort, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: foo__bindgen_ty_1::a", + ][::std::mem::offset_of!(foo__bindgen_ty_1, a) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 0usize]; +}; impl Default for foo__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -44,26 +32,12 @@ impl Default for foo__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::bar"][::std::mem::offset_of!(foo, bar) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_union_1_0.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_union_1_0.rs deleted file mode 100644 index d0158ce178..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_union_1_0.rs +++ /dev/null @@ -1,112 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub bar: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1 { - pub a: __BindgenUnionField<::std::os::raw::c_uint>, - pub b: __BindgenUnionField<::std::os::raw::c_ushort>, - pub bindgen_union_field: u32, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); -} -impl Clone for foo__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_struct.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_struct.rs index 4f8aa8ff8a..859188e891 100644 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_struct.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_struct.rs @@ -13,81 +13,33 @@ pub struct pixel__bindgen_ty_1 { pub b: ::std::os::raw::c_uchar, pub a: ::std::os::raw::c_uchar, } -#[test] -fn bindgen_test_layout_pixel__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(pixel__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(pixel__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).r) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(pixel__bindgen_ty_1), - "::", - stringify!(r), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).g) as usize - ptr as usize }, - 1usize, - concat!( - "Offset of field: ", - stringify!(pixel__bindgen_ty_1), - "::", - stringify!(g), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(pixel__bindgen_ty_1), - "::", - stringify!(b), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 3usize, - concat!( - "Offset of field: ", - stringify!(pixel__bindgen_ty_1), - "::", - stringify!(a), - ), - ); -} -#[test] -fn bindgen_test_layout_pixel() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(pixel)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(pixel)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rgba) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(pixel), "::", stringify!(rgba)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of pixel__bindgen_ty_1", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of pixel__bindgen_ty_1", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: pixel__bindgen_ty_1::r", + ][::std::mem::offset_of!(pixel__bindgen_ty_1, r) - 0usize]; + [ + "Offset of field: pixel__bindgen_ty_1::g", + ][::std::mem::offset_of!(pixel__bindgen_ty_1, g) - 1usize]; + [ + "Offset of field: pixel__bindgen_ty_1::b", + ][::std::mem::offset_of!(pixel__bindgen_ty_1, b) - 2usize]; + [ + "Offset of field: pixel__bindgen_ty_1::a", + ][::std::mem::offset_of!(pixel__bindgen_ty_1, a) - 3usize]; +}; +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of pixel"][::std::mem::size_of::() - 4usize]; + ["Alignment of pixel"][::std::mem::align_of::() - 4usize]; + ["Offset of field: pixel::rgba"][::std::mem::offset_of!(pixel, rgba) - 0usize]; +}; impl Default for pixel { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_struct_1_0.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_struct_1_0.rs deleted file mode 100644 index 23b1887b5a..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_struct_1_0.rs +++ /dev/null @@ -1,144 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct pixel { - pub rgba: __BindgenUnionField<::std::os::raw::c_uint>, - pub __bindgen_anon_1: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct pixel__bindgen_ty_1 { - pub r: ::std::os::raw::c_uchar, - pub g: ::std::os::raw::c_uchar, - pub b: ::std::os::raw::c_uchar, - pub a: ::std::os::raw::c_uchar, -} -#[test] -fn bindgen_test_layout_pixel__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(pixel__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(pixel__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).r) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(pixel__bindgen_ty_1), - "::", - stringify!(r), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).g) as usize - ptr as usize }, - 1usize, - concat!( - "Offset of field: ", - stringify!(pixel__bindgen_ty_1), - "::", - stringify!(g), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 2usize, - concat!( - "Offset of field: ", - stringify!(pixel__bindgen_ty_1), - "::", - stringify!(b), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 3usize, - concat!( - "Offset of field: ", - stringify!(pixel__bindgen_ty_1), - "::", - stringify!(a), - ), - ); -} -impl Clone for pixel__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_pixel() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(pixel)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(pixel)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).rgba) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(pixel), "::", stringify!(rgba)), - ); -} -impl Clone for pixel { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_union.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_union.rs index d9d22e323e..6e136c0d92 100644 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_union.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_union.rs @@ -11,31 +11,19 @@ pub union foo__bindgen_ty_1 { pub b: ::std::os::raw::c_ushort, pub c: ::std::os::raw::c_uchar, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(c)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 2usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: foo__bindgen_ty_1::b", + ][::std::mem::offset_of!(foo__bindgen_ty_1, b) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1::c", + ][::std::mem::offset_of!(foo__bindgen_ty_1, c) - 0usize]; +}; impl Default for foo__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -45,26 +33,12 @@ impl Default for foo__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::a"][::std::mem::offset_of!(foo, a) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_union_1_0.rs b/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_union_1_0.rs deleted file mode 100644 index 179a87c92c..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_with_anon_unnamed_union_1_0.rs +++ /dev/null @@ -1,113 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub a: __BindgenUnionField<::std::os::raw::c_uint>, - pub __bindgen_anon_1: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1 { - pub b: __BindgenUnionField<::std::os::raw::c_ushort>, - pub c: __BindgenUnionField<::std::os::raw::c_uchar>, - pub bindgen_union_field: u16, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(c)), - ); -} -impl Clone for foo__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_with_big_member.rs b/bindgen-tests/tests/expectations/tests/union_with_big_member.rs index 955e57a0a0..9d69957a85 100644 --- a/bindgen-tests/tests/expectations/tests/union_with_big_member.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_big_member.rs @@ -5,31 +5,17 @@ pub union WithBigArray { pub a: ::std::os::raw::c_int, pub b: [::std::os::raw::c_int; 33usize], } -#[test] -fn bindgen_test_layout_WithBigArray() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 132usize, - concat!("Size of: ", stringify!(WithBigArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithBigArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigArray), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigArray), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithBigArray"][::std::mem::size_of::() - 132usize]; + ["Alignment of WithBigArray"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WithBigArray::a", + ][::std::mem::offset_of!(WithBigArray, a) - 0usize]; + [ + "Offset of field: WithBigArray::b", + ][::std::mem::offset_of!(WithBigArray, b) - 0usize]; +}; impl Default for WithBigArray { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -45,31 +31,17 @@ pub union WithBigArray2 { pub a: ::std::os::raw::c_int, pub b: [::std::os::raw::c_char; 33usize], } -#[test] -fn bindgen_test_layout_WithBigArray2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 36usize, - concat!("Size of: ", stringify!(WithBigArray2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithBigArray2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigArray2), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigArray2), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithBigArray2"][::std::mem::size_of::() - 36usize]; + ["Alignment of WithBigArray2"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WithBigArray2::a", + ][::std::mem::offset_of!(WithBigArray2, a) - 0usize]; + [ + "Offset of field: WithBigArray2::b", + ][::std::mem::offset_of!(WithBigArray2, b) - 0usize]; +}; impl Default for WithBigArray2 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -85,31 +57,17 @@ pub union WithBigMember { pub a: ::std::os::raw::c_int, pub b: WithBigArray, } -#[test] -fn bindgen_test_layout_WithBigMember() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 132usize, - concat!("Size of: ", stringify!(WithBigMember)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithBigMember)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigMember), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigMember), "::", stringify!(b)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithBigMember"][::std::mem::size_of::() - 132usize]; + ["Alignment of WithBigMember"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WithBigMember::a", + ][::std::mem::offset_of!(WithBigMember, a) - 0usize]; + [ + "Offset of field: WithBigMember::b", + ][::std::mem::offset_of!(WithBigMember, b) - 0usize]; +}; impl Default for WithBigMember { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_with_big_member_1_0.rs b/bindgen-tests/tests/expectations/tests/union_with_big_member_1_0.rs deleted file mode 100644 index 2b50d4e754..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_with_big_member_1_0.rs +++ /dev/null @@ -1,173 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Copy)] -pub struct WithBigArray { - pub a: __BindgenUnionField<::std::os::raw::c_int>, - pub b: __BindgenUnionField<[::std::os::raw::c_int; 33usize]>, - pub bindgen_union_field: [u32; 33usize], -} -#[test] -fn bindgen_test_layout_WithBigArray() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 132usize, - concat!("Size of: ", stringify!(WithBigArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithBigArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigArray), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigArray), "::", stringify!(b)), - ); -} -impl Clone for WithBigArray { - fn clone(&self) -> Self { - *self - } -} -impl Default for WithBigArray { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct WithBigArray2 { - pub a: __BindgenUnionField<::std::os::raw::c_int>, - pub b: __BindgenUnionField<[::std::os::raw::c_char; 33usize]>, - pub bindgen_union_field: [u32; 9usize], -} -#[test] -fn bindgen_test_layout_WithBigArray2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 36usize, - concat!("Size of: ", stringify!(WithBigArray2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithBigArray2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigArray2), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigArray2), "::", stringify!(b)), - ); -} -impl Clone for WithBigArray2 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Copy)] -pub struct WithBigMember { - pub a: __BindgenUnionField<::std::os::raw::c_int>, - pub b: __BindgenUnionField, - pub bindgen_union_field: [u32; 33usize], -} -#[test] -fn bindgen_test_layout_WithBigMember() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 132usize, - concat!("Size of: ", stringify!(WithBigMember)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithBigMember)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigMember), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithBigMember), "::", stringify!(b)), - ); -} -impl Clone for WithBigMember { - fn clone(&self) -> Self { - *self - } -} -impl Default for WithBigMember { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_with_nesting.rs b/bindgen-tests/tests/expectations/tests/union_with_nesting.rs index 929484d12c..5b60193ba4 100644 --- a/bindgen-tests/tests/expectations/tests/union_with_nesting.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_nesting.rs @@ -17,41 +17,21 @@ pub union foo__bindgen_ty_1__bindgen_ty_1 { pub b1: ::std::os::raw::c_ushort, pub b2: ::std::os::raw::c_ushort, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(b1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b2) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(b2), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of foo__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::size_of::() - 2usize]; + [ + "Alignment of foo__bindgen_ty_1__bindgen_ty_1", + ][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_1::b1", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_1, b1) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_1::b2", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_1, b2) - 0usize]; +}; impl Default for foo__bindgen_ty_1__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -67,41 +47,21 @@ pub union foo__bindgen_ty_1__bindgen_ty_2 { pub c1: ::std::os::raw::c_ushort, pub c2: ::std::os::raw::c_ushort, } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(c1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c2) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(c2), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of foo__bindgen_ty_1__bindgen_ty_2", + ][::std::mem::size_of::() - 2usize]; + [ + "Alignment of foo__bindgen_ty_1__bindgen_ty_2", + ][::std::mem::align_of::() - 2usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_2::c1", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_2, c1) - 0usize]; + [ + "Offset of field: foo__bindgen_ty_1__bindgen_ty_2::c2", + ][::std::mem::offset_of!(foo__bindgen_ty_1__bindgen_ty_2, c2) - 0usize]; +}; impl Default for foo__bindgen_ty_1__bindgen_ty_2 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -111,19 +71,13 @@ impl Default for foo__bindgen_ty_1__bindgen_ty_2 { } } } -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo__bindgen_ty_1"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of foo__bindgen_ty_1", + ][::std::mem::align_of::() - 2usize]; +}; impl Default for foo__bindgen_ty_1 { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -133,26 +87,12 @@ impl Default for foo__bindgen_ty_1 { } } } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 4usize]; + ["Alignment of foo"][::std::mem::align_of::() - 4usize]; + ["Offset of field: foo::a"][::std::mem::offset_of!(foo, a) - 0usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_with_nesting_1_0.rs b/bindgen-tests/tests/expectations/tests/union_with_nesting_1_0.rs deleted file mode 100644 index 4305d58f91..0000000000 --- a/bindgen-tests/tests/expectations/tests/union_with_nesting_1_0.rs +++ /dev/null @@ -1,194 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::std::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::std::mem::transmute(self) - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub a: __BindgenUnionField<::std::os::raw::c_uint>, - pub __bindgen_anon_1: __BindgenUnionField, - pub bindgen_union_field: u32, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1 { - pub __bindgen_anon_1: foo__bindgen_ty_1__bindgen_ty_1, - pub __bindgen_anon_2: foo__bindgen_ty_1__bindgen_ty_2, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1__bindgen_ty_1 { - pub b1: __BindgenUnionField<::std::os::raw::c_ushort>, - pub b2: __BindgenUnionField<::std::os::raw::c_ushort>, - pub bindgen_union_field: u16, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1__bindgen_ty_1() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1__bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(b1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b2) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(b2), - ), - ); -} -impl Clone for foo__bindgen_ty_1__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct foo__bindgen_ty_1__bindgen_ty_2 { - pub c1: __BindgenUnionField<::std::os::raw::c_ushort>, - pub c2: __BindgenUnionField<::std::os::raw::c_ushort>, - pub bindgen_union_field: u16, -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1__bindgen_ty_2() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 2usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1__bindgen_ty_2)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c1) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(c1), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).c2) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(foo__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(c2), - ), - ); -} -impl Clone for foo__bindgen_ty_1__bindgen_ty_2 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo__bindgen_ty_1() { - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo__bindgen_ty_1)), - ); - assert_eq!( - ::std::mem::align_of::(), - 2usize, - concat!("Alignment of ", stringify!(foo__bindgen_ty_1)), - ); -} -impl Clone for foo__bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/union_with_non_copy_member.rs b/bindgen-tests/tests/expectations/tests/union_with_non_copy_member.rs index d9eaeacdf1..d13c24d2d8 100644 --- a/bindgen-tests/tests/expectations/tests/union_with_non_copy_member.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_non_copy_member.rs @@ -47,67 +47,35 @@ impl ::std::cmp::Eq for __BindgenUnionField {} pub struct NonCopyType { pub foo: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_NonCopyType() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(NonCopyType)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(NonCopyType)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).foo) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(NonCopyType), "::", stringify!(foo)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of NonCopyType"][::std::mem::size_of::() - 4usize]; + ["Alignment of NonCopyType"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: NonCopyType::foo", + ][::std::mem::offset_of!(NonCopyType, foo) - 0usize]; +}; #[repr(C)] pub struct WithBindgenGeneratedWrapper { pub non_copy_type: __BindgenUnionField, pub bar: __BindgenUnionField<::std::os::raw::c_int>, pub bindgen_union_field: u32, } -#[test] -fn bindgen_test_layout_WithBindgenGeneratedWrapper() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithBindgenGeneratedWrapper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithBindgenGeneratedWrapper)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).non_copy_type) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithBindgenGeneratedWrapper), - "::", - stringify!(non_copy_type), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithBindgenGeneratedWrapper), - "::", - stringify!(bar), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of WithBindgenGeneratedWrapper", + ][::std::mem::size_of::() - 4usize]; + [ + "Alignment of WithBindgenGeneratedWrapper", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WithBindgenGeneratedWrapper::non_copy_type", + ][::std::mem::offset_of!(WithBindgenGeneratedWrapper, non_copy_type) - 0usize]; + [ + "Offset of field: WithBindgenGeneratedWrapper::bar", + ][::std::mem::offset_of!(WithBindgenGeneratedWrapper, bar) - 0usize]; +}; impl Default for WithBindgenGeneratedWrapper { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -122,36 +90,19 @@ pub union WithManuallyDrop { pub non_copy_type: ::std::mem::ManuallyDrop, pub bar: ::std::mem::ManuallyDrop<::std::os::raw::c_int>, } -#[test] -fn bindgen_test_layout_WithManuallyDrop() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithManuallyDrop)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithManuallyDrop)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).non_copy_type) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithManuallyDrop), - "::", - stringify!(non_copy_type), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(WithManuallyDrop), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithManuallyDrop"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of WithManuallyDrop", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WithManuallyDrop::non_copy_type", + ][::std::mem::offset_of!(WithManuallyDrop, non_copy_type) - 0usize]; + [ + "Offset of field: WithManuallyDrop::bar", + ][::std::mem::offset_of!(WithManuallyDrop, bar) - 0usize]; +}; impl Default for WithManuallyDrop { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -167,41 +118,19 @@ pub struct WithDefaultWrapper { pub bar: __BindgenUnionField<::std::os::raw::c_int>, pub bindgen_union_field: u32, } -#[test] -fn bindgen_test_layout_WithDefaultWrapper() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(WithDefaultWrapper)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(WithDefaultWrapper)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).non_copy_type) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithDefaultWrapper), - "::", - stringify!(non_copy_type), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(WithDefaultWrapper), - "::", - stringify!(bar), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of WithDefaultWrapper"][::std::mem::size_of::() - 4usize]; + [ + "Alignment of WithDefaultWrapper", + ][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: WithDefaultWrapper::non_copy_type", + ][::std::mem::offset_of!(WithDefaultWrapper, non_copy_type) - 0usize]; + [ + "Offset of field: WithDefaultWrapper::bar", + ][::std::mem::offset_of!(WithDefaultWrapper, bar) - 0usize]; +}; impl Default for WithDefaultWrapper { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/union_template_1_0.rs b/bindgen-tests/tests/expectations/tests/union_with_zero_sized_array.rs similarity index 55% rename from bindgen-tests/tests/expectations/tests/union_template_1_0.rs rename to bindgen-tests/tests/expectations/tests/union_with_zero_sized_array.rs index 4ebad2a2e2..aa23fcd734 100644 --- a/bindgen-tests/tests/expectations/tests/union_template_1_0.rs +++ b/bindgen-tests/tests/expectations/tests/union_with_zero_sized_array.rs @@ -3,7 +3,7 @@ pub struct __BindgenUnionField(::std::marker::PhantomData); impl __BindgenUnionField { #[inline] - pub fn new() -> Self { + pub const fn new() -> Self { __BindgenUnionField(::std::marker::PhantomData) } #[inline] @@ -43,30 +43,26 @@ impl ::std::cmp::PartialEq for __BindgenUnionField { } impl ::std::cmp::Eq for __BindgenUnionField {} #[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct NastyStruct { - pub mIsSome: bool, - pub mStorage: NastyStruct__bindgen_ty_1, - pub __bindgen_anon_1: NastyStruct__bindgen_ty_2, +pub struct U { + pub d0: __BindgenUnionField<[::std::os::raw::c_char; 0usize]>, + pub d1: __BindgenUnionField<[::std::os::raw::c_char; 1usize]>, + pub d2: __BindgenUnionField<[::std::os::raw::c_char; 2usize]>, + pub bindgen_union_field: [u8; 2usize], } -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct NastyStruct__bindgen_ty_1 { - pub mFoo: __BindgenUnionField<*mut ::std::os::raw::c_void>, - pub mDummy: __BindgenUnionField<::std::os::raw::c_ulong>, - pub bindgen_union_field: u64, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct NastyStruct__bindgen_ty_2 { - pub wat: __BindgenUnionField<::std::os::raw::c_short>, - pub wut: __BindgenUnionField<*mut ::std::os::raw::c_int>, - pub bindgen_union_field: u64, -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] -pub struct Whatever { - pub mTPtr: __BindgenUnionField<*mut ::std::os::raw::c_void>, - pub mInt: __BindgenUnionField<::std::os::raw::c_int>, - pub bindgen_union_field: u64, +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of U"][::std::mem::size_of::() - 2usize]; + ["Alignment of U"][::std::mem::align_of::() - 1usize]; + ["Offset of field: U::d0"][::std::mem::offset_of!(U, d0) - 0usize]; + ["Offset of field: U::d1"][::std::mem::offset_of!(U, d1) - 0usize]; + ["Offset of field: U::d2"][::std::mem::offset_of!(U, d2) - 0usize]; +}; +impl Default for U { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } } diff --git a/bindgen-tests/tests/expectations/tests/unknown_attr.rs b/bindgen-tests/tests/expectations/tests/unknown_attr.rs index 7b21595d9f..bdfebb29dc 100644 --- a/bindgen-tests/tests/expectations/tests/unknown_attr.rs +++ b/bindgen-tests/tests/expectations/tests/unknown_attr.rs @@ -7,42 +7,14 @@ pub struct max_align_t { pub __bindgen_padding_0: u64, pub __clang_max_align_nonce2: ::std::os::raw::c_longlong, } -#[test] -fn bindgen_test_layout_max_align_t() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 32usize, - concat!("Size of: ", stringify!(max_align_t)), - ); - assert_eq!( - ::std::mem::align_of::(), - 16usize, - concat!("Alignment of ", stringify!(max_align_t)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).__clang_max_align_nonce1) as usize - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(max_align_t), - "::", - stringify!(__clang_max_align_nonce1), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).__clang_max_align_nonce2) as usize - ptr as usize - }, - 16usize, - concat!( - "Offset of field: ", - stringify!(max_align_t), - "::", - stringify!(__clang_max_align_nonce2), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of max_align_t"][::std::mem::size_of::() - 32usize]; + ["Alignment of max_align_t"][::std::mem::align_of::() - 16usize]; + [ + "Offset of field: max_align_t::__clang_max_align_nonce1", + ][::std::mem::offset_of!(max_align_t, __clang_max_align_nonce1) - 0usize]; + [ + "Offset of field: max_align_t::__clang_max_align_nonce2", + ][::std::mem::offset_of!(max_align_t, __clang_max_align_nonce2) - 16usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/unsorted-items.rs b/bindgen-tests/tests/expectations/tests/unsorted-items.rs index 745ddd92e2..7d31c222a1 100644 --- a/bindgen-tests/tests/expectations/tests/unsorted-items.rs +++ b/bindgen-tests/tests/expectations/tests/unsorted-items.rs @@ -1,9 +1,9 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn foo() -> ::std::os::raw::c_int; } pub type number = ::std::os::raw::c_int; -extern "C" { +unsafe extern "C" { pub fn bar(x: number) -> ::std::os::raw::c_int; } #[repr(C)] @@ -12,63 +12,27 @@ pub struct Point { pub x: number, pub y: number, } -#[test] -fn bindgen_test_layout_Point() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Point)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Point)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Point), "::", stringify!(x)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).y) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Point), "::", stringify!(y)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Point"][::std::mem::size_of::() - 8usize]; + ["Alignment of Point"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Point::x"][::std::mem::offset_of!(Point, x) - 0usize]; + ["Offset of field: Point::y"][::std::mem::offset_of!(Point, y) - 4usize]; +}; #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Angle { pub a: number, pub b: number, } -#[test] -fn bindgen_test_layout_Angle() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Angle)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Angle)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Angle), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(Angle), "::", stringify!(b)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Angle"][::std::mem::size_of::() - 8usize]; + ["Alignment of Angle"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Angle::a"][::std::mem::offset_of!(Angle, a) - 0usize]; + ["Offset of field: Angle::b"][::std::mem::offset_of!(Angle, b) - 4usize]; +}; +unsafe extern "C" { pub fn baz(point: Point) -> ::std::os::raw::c_int; } pub const NUMBER: number = 42; diff --git a/bindgen-tests/tests/expectations/tests/use-core.rs b/bindgen-tests/tests/expectations/tests/use-core.rs index 2b6e93bfc4..8d495459a0 100644 --- a/bindgen-tests/tests/expectations/tests/use-core.rs +++ b/bindgen-tests/tests/expectations/tests/use-core.rs @@ -8,36 +8,14 @@ pub struct foo { pub b: ::core::ffi::c_int, pub bar: *mut ::core::ffi::c_void, } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::core::mem::MaybeUninit = ::core::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::core::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::core::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::core::mem::size_of::() - 16usize]; + ["Alignment of foo"][::core::mem::align_of::() - 8usize]; + ["Offset of field: foo::a"][::core::mem::offset_of!(foo, a) - 0usize]; + ["Offset of field: foo::b"][::core::mem::offset_of!(foo, b) - 4usize]; + ["Offset of field: foo::bar"][::core::mem::offset_of!(foo, bar) - 8usize]; +}; impl Default for foo { fn default() -> Self { let mut s = ::core::mem::MaybeUninit::::uninit(); @@ -53,31 +31,17 @@ pub union _bindgen_ty_1 { pub bar: ::core::ffi::c_int, pub baz: ::core::ffi::c_long, } -#[test] -fn bindgen_test_layout__bindgen_ty_1() { - const UNINIT: ::core::mem::MaybeUninit<_bindgen_ty_1> = ::core::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::core::mem::size_of::<_bindgen_ty_1>(), - 8usize, - concat!("Size of: ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - ::core::mem::align_of::<_bindgen_ty_1>(), - 8usize, - concat!("Alignment of ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(_bindgen_ty_1), "::", stringify!(bar)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(_bindgen_ty_1), "::", stringify!(baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of _bindgen_ty_1"][::core::mem::size_of::<_bindgen_ty_1>() - 8usize]; + ["Alignment of _bindgen_ty_1"][::core::mem::align_of::<_bindgen_ty_1>() - 8usize]; + [ + "Offset of field: _bindgen_ty_1::bar", + ][::core::mem::offset_of!(_bindgen_ty_1, bar) - 0usize]; + [ + "Offset of field: _bindgen_ty_1::baz", + ][::core::mem::offset_of!(_bindgen_ty_1, baz) - 0usize]; +}; impl Default for _bindgen_ty_1 { fn default() -> Self { let mut s = ::core::mem::MaybeUninit::::uninit(); @@ -87,7 +51,7 @@ impl Default for _bindgen_ty_1 { } } } -extern "C" { +unsafe extern "C" { pub static mut bazz: _bindgen_ty_1; } pub type fooFunction = ::core::option::Option< diff --git a/bindgen-tests/tests/expectations/tests/use-core_1_0.rs b/bindgen-tests/tests/expectations/tests/use-core_1_0.rs deleted file mode 100644 index 6c56e43eea..0000000000 --- a/bindgen-tests/tests/expectations/tests/use-core_1_0.rs +++ /dev/null @@ -1,139 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern crate core; -#[repr(C)] -pub struct __BindgenUnionField(::core::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::core::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - ::core::mem::transmute(self) - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - ::core::mem::transmute(self) - } -} -impl ::core::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::core::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::core::marker::Copy for __BindgenUnionField {} -impl ::core::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::core::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::core::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::core::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Copy, Hash, PartialEq, Eq)] -pub struct foo { - pub a: ::std::os::raw::c_int, - pub b: ::std::os::raw::c_int, - pub bar: *mut ::std::os::raw::c_void, -} -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::core::mem::MaybeUninit = ::core::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::core::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::core::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).a) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).b) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(b)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)), - ); -} -impl Clone for foo { - fn clone(&self) -> Self { - *self - } -} -impl Default for foo { - fn default() -> Self { - unsafe { - let mut s: Self = ::core::mem::uninitialized(); - ::core::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] -pub struct _bindgen_ty_1 { - pub bar: __BindgenUnionField<::std::os::raw::c_int>, - pub baz: __BindgenUnionField<::std::os::raw::c_long>, - pub bindgen_union_field: u64, -} -#[test] -fn bindgen_test_layout__bindgen_ty_1() { - const UNINIT: ::core::mem::MaybeUninit<_bindgen_ty_1> = ::core::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::core::mem::size_of::<_bindgen_ty_1>(), - 8usize, - concat!("Size of: ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - ::core::mem::align_of::<_bindgen_ty_1>(), - 8usize, - concat!("Alignment of ", stringify!(_bindgen_ty_1)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).bar) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(_bindgen_ty_1), "::", stringify!(bar)), - ); - assert_eq!( - unsafe { ::core::ptr::addr_of!((*ptr).baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(_bindgen_ty_1), "::", stringify!(baz)), - ); -} -impl Clone for _bindgen_ty_1 { - fn clone(&self) -> Self { - *self - } -} -extern "C" { - pub static mut bazz: _bindgen_ty_1; -} -pub type fooFunction = ::core::option::Option< - unsafe extern "C" fn(bar: ::std::os::raw::c_int), ->; diff --git a/bindgen-tests/tests/expectations/tests/using.rs b/bindgen-tests/tests/expectations/tests/using.rs index 97d00cb5b8..9737fef0a5 100644 --- a/bindgen-tests/tests/expectations/tests/using.rs +++ b/bindgen-tests/tests/expectations/tests/using.rs @@ -2,9 +2,9 @@ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Point { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub x: T, pub y: T, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for Point { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/va_list_aarch64_linux.rs b/bindgen-tests/tests/expectations/tests/va_list_aarch64_linux.rs new file mode 100644 index 0000000000..31f75ced23 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/va_list_aarch64_linux.rs @@ -0,0 +1,18 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +/// If Bindgen could only determine the size and alignment of a +/// type, it is represented like this. +#[derive(PartialEq, Copy, Clone, Debug, Hash)] +#[repr(C)] +pub struct __BindgenOpaqueArray(pub [T; N]); +impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } +} +pub type va_list = __BindgenOpaqueArray; +unsafe extern "C" { + pub fn vprintf( + format: *const ::std::os::raw::c_char, + vlist: __BindgenOpaqueArray, + ) -> ::std::os::raw::c_int; +} diff --git a/bindgen-tests/tests/expectations/tests/var-tracing.rs b/bindgen-tests/tests/expectations/tests/var-tracing.rs index fcd5d59471..76ce0c50d6 100644 --- a/bindgen-tests/tests/expectations/tests/var-tracing.rs +++ b/bindgen-tests/tests/expectations/tests/var-tracing.rs @@ -4,27 +4,13 @@ pub struct Bar { pub m_baz: ::std::os::raw::c_int, } -#[test] -fn bindgen_test_layout_Bar() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Bar)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).m_baz) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(Bar), "::", stringify!(m_baz)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 4usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 4usize]; + ["Offset of field: Bar::m_baz"][::std::mem::offset_of!(Bar, m_baz) - 0usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3BarC1Ei"] pub fn Bar_Bar(this: *mut Bar, baz: ::std::os::raw::c_int); } @@ -41,20 +27,12 @@ impl Bar { pub struct Baz { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN3Baz3FOOE"] pub static Baz_FOO: [Bar; 0usize]; } -#[test] -fn bindgen_test_layout_Baz() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Baz)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Baz)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Baz"][::std::mem::size_of::() - 1usize]; + ["Alignment of Baz"][::std::mem::align_of::() - 1usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/variadic-method.rs b/bindgen-tests/tests/expectations/tests/variadic-method.rs index c9b4e87bf9..deac5f719e 100644 --- a/bindgen-tests/tests/expectations/tests/variadic-method.rs +++ b/bindgen-tests/tests/expectations/tests/variadic-method.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z3fooPKcz"] pub fn foo(fmt: *const ::std::os::raw::c_char, ...); } @@ -8,20 +8,12 @@ extern "C" { pub struct Bar { pub _address: u8, } -#[test] -fn bindgen_test_layout_Bar() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Bar)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Bar)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Bar"][::std::mem::size_of::() - 1usize]; + ["Alignment of Bar"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3Bar3fooEPKcz"] pub fn Bar_foo(this: *mut Bar, fmt: *const ::std::os::raw::c_char, ...); } diff --git a/bindgen-tests/tests/expectations/tests/vector.rs b/bindgen-tests/tests/expectations/tests/vector.rs index fc400acebf..da53b4a8eb 100644 --- a/bindgen-tests/tests/expectations/tests/vector.rs +++ b/bindgen-tests/tests/expectations/tests/vector.rs @@ -4,30 +4,16 @@ pub struct foo { pub mMember: [::std::os::raw::c_longlong; 1usize], } -#[test] -fn bindgen_test_layout_foo() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(foo)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mMember) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(foo), "::", stringify!(mMember)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of foo"][::std::mem::size_of::() - 8usize]; + ["Alignment of foo"][::std::mem::align_of::() - 8usize]; + ["Offset of field: foo::mMember"][::std::mem::offset_of!(foo, mMember) - 0usize]; +}; pub type __m128 = [f32; 4usize]; pub type __m128d = [f64; 2usize]; pub type __m128i = [::std::os::raw::c_longlong; 2usize]; -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_Z3fooDv2_xDv2_d"] pub fn foo(arg1: __m128i, arg2: __m128d) -> __m128; } diff --git a/bindgen-tests/tests/expectations/tests/virtual_dtor.rs b/bindgen-tests/tests/expectations/tests/virtual_dtor.rs index cff0bc1205..d42be25202 100644 --- a/bindgen-tests/tests/expectations/tests/virtual_dtor.rs +++ b/bindgen-tests/tests/expectations/tests/virtual_dtor.rs @@ -6,19 +6,11 @@ pub struct nsSlots__bindgen_vtable(::std::os::raw::c_void); pub struct nsSlots { pub vtable_: *const nsSlots__bindgen_vtable, } -#[test] -fn bindgen_test_layout_nsSlots() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(nsSlots)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(nsSlots)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of nsSlots"][::std::mem::size_of::() - 8usize]; + ["Alignment of nsSlots"][::std::mem::align_of::() - 8usize]; +}; impl Default for nsSlots { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -28,7 +20,7 @@ impl Default for nsSlots { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN7nsSlotsD1Ev"] pub fn nsSlots_nsSlots_destructor(this: *mut nsSlots); } diff --git a/bindgen-tests/tests/expectations/tests/virtual_interface.rs b/bindgen-tests/tests/expectations/tests/virtual_interface.rs index e3440567b4..44b245c4ea 100644 --- a/bindgen-tests/tests/expectations/tests/virtual_interface.rs +++ b/bindgen-tests/tests/expectations/tests/virtual_interface.rs @@ -12,19 +12,13 @@ pub struct PureVirtualIFace__bindgen_vtable { pub struct PureVirtualIFace { pub vtable_: *const PureVirtualIFace__bindgen_vtable, } -#[test] -fn bindgen_test_layout_PureVirtualIFace() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(PureVirtualIFace)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(PureVirtualIFace)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of PureVirtualIFace"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of PureVirtualIFace", + ][::std::mem::align_of::() - 8usize]; +}; impl Default for PureVirtualIFace { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -43,19 +37,13 @@ pub struct AnotherInterface__bindgen_vtable { pub struct AnotherInterface { pub vtable_: *const AnotherInterface__bindgen_vtable, } -#[test] -fn bindgen_test_layout_AnotherInterface() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(AnotherInterface)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(AnotherInterface)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of AnotherInterface"][::std::mem::size_of::() - 8usize]; + [ + "Alignment of AnotherInterface", + ][::std::mem::align_of::() - 8usize]; +}; impl Default for AnotherInterface { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -70,19 +58,11 @@ impl Default for AnotherInterface { pub struct Implementation { pub _base: PureVirtualIFace, } -#[test] -fn bindgen_test_layout_Implementation() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Implementation)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Implementation)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Implementation"][::std::mem::size_of::() - 8usize]; + ["Alignment of Implementation"][::std::mem::align_of::() - 8usize]; +}; impl Default for Implementation { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -98,19 +78,11 @@ pub struct DoubleImpl { pub _base: PureVirtualIFace, pub _base_1: AnotherInterface, } -#[test] -fn bindgen_test_layout_DoubleImpl() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(DoubleImpl)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(DoubleImpl)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of DoubleImpl"][::std::mem::size_of::() - 16usize]; + ["Alignment of DoubleImpl"][::std::mem::align_of::() - 8usize]; +}; impl Default for DoubleImpl { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/virtual_overloaded.rs b/bindgen-tests/tests/expectations/tests/virtual_overloaded.rs index 28a873c458..4c3702faeb 100644 --- a/bindgen-tests/tests/expectations/tests/virtual_overloaded.rs +++ b/bindgen-tests/tests/expectations/tests/virtual_overloaded.rs @@ -9,15 +9,11 @@ pub struct C__bindgen_vtable { pub struct C { pub vtable_: *const C__bindgen_vtable, } -#[test] -fn bindgen_test_layout_C() { - assert_eq!(::std::mem::size_of::(), 8usize, concat!("Size of: ", stringify!(C))); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(C)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of C"][::std::mem::size_of::() - 8usize]; + ["Alignment of C"][::std::mem::align_of::() - 8usize]; +}; impl Default for C { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -27,11 +23,11 @@ impl Default for C { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1C8do_thingEc"] pub fn C_do_thing(this: *mut ::std::os::raw::c_void, arg1: ::std::os::raw::c_char); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN1C8do_thingEi"] pub fn C_do_thing1(this: *mut ::std::os::raw::c_void, arg1: ::std::os::raw::c_int); } diff --git a/bindgen-tests/tests/expectations/tests/void_typedef.rs b/bindgen-tests/tests/expectations/tests/void_typedef.rs index 6c3b45dcc7..4997d49086 100644 --- a/bindgen-tests/tests/expectations/tests/void_typedef.rs +++ b/bindgen-tests/tests/expectations/tests/void_typedef.rs @@ -1,12 +1,12 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] pub type VOID = ::std::os::raw::c_void; pub type ALSO_VOID = VOID; -extern "C" { +unsafe extern "C" { pub fn this_api_returns_nothing(); } -extern "C" { +unsafe extern "C" { pub fn this_api_also_returns_nothing(); } -extern "C" { +unsafe extern "C" { pub fn this_other_api_also_returns_nothing(); } diff --git a/bindgen-tests/tests/expectations/tests/vtable_recursive_sig.rs b/bindgen-tests/tests/expectations/tests/vtable_recursive_sig.rs index a37ecf2669..9b9c2467aa 100644 --- a/bindgen-tests/tests/expectations/tests/vtable_recursive_sig.rs +++ b/bindgen-tests/tests/expectations/tests/vtable_recursive_sig.rs @@ -8,19 +8,11 @@ pub struct Base__bindgen_vtable { pub struct Base { pub vtable_: *const Base__bindgen_vtable, } -#[test] -fn bindgen_test_layout_Base() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Base)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Base)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Base"][::std::mem::size_of::() - 8usize]; + ["Alignment of Base"][::std::mem::align_of::() - 8usize]; +}; impl Default for Base { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -30,7 +22,7 @@ impl Default for Base { } } } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN4Base9AsDerivedEv"] pub fn Base_AsDerived(this: *mut ::std::os::raw::c_void) -> *mut Derived; } @@ -39,19 +31,11 @@ extern "C" { pub struct Derived { pub _base: Base, } -#[test] -fn bindgen_test_layout_Derived() { - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(Derived)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(Derived)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Derived"][::std::mem::size_of::() - 8usize]; + ["Alignment of Derived"][::std::mem::align_of::() - 8usize]; +}; impl Default for Derived { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); diff --git a/bindgen-tests/tests/expectations/tests/wasm-constructor-returns.rs b/bindgen-tests/tests/expectations/tests/wasm-constructor-returns.rs index 7c47a43c20..ee26600a6b 100644 --- a/bindgen-tests/tests/expectations/tests/wasm-constructor-returns.rs +++ b/bindgen-tests/tests/expectations/tests/wasm-constructor-returns.rs @@ -4,20 +4,12 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "C" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "C" { #[link_name = "\u{1}_ZN3FooC1Ei"] pub fn Foo_Foo( this: *mut Foo, diff --git a/bindgen-tests/tests/expectations/tests/wasm-import-module.rs b/bindgen-tests/tests/expectations/tests/wasm-import-module.rs index 9725195e0e..aeeb17f1c1 100644 --- a/bindgen-tests/tests/expectations/tests/wasm-import-module.rs +++ b/bindgen-tests/tests/expectations/tests/wasm-import-module.rs @@ -1,5 +1,5 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #[link(wasm_import_module = "test-module")] -extern "C" { +unsafe extern "C" { pub fn test_function(); } diff --git a/bindgen-tests/tests/expectations/tests/weird_bitfields.rs b/bindgen-tests/tests/expectations/tests/weird_bitfields.rs index 49579967fe..17accb01d9 100644 --- a/bindgen-tests/tests/expectations/tests/weird_bitfields.rs +++ b/bindgen-tests/tests/expectations/tests/weird_bitfields.rs @@ -15,10 +15,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -28,21 +25,48 @@ where byte & mask == mask } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) + }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; - if val { - *byte |= mask; - } else { - *byte &= !mask; - } + if val { byte | mask } else { byte & !mask } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { @@ -65,6 +89,26 @@ where val } #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); @@ -82,6 +126,24 @@ where self.set_bit(index + bit_offset, val_bit_is_set); } } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::(), + ); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } } #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] @@ -111,118 +173,47 @@ pub struct Weird { pub _bitfield_2: __BindgenBitfieldUnit<[u8; 2usize]>, pub __bindgen_padding_0: [u8; 3usize], } -#[test] -fn bindgen_test_layout_Weird() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(Weird)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(Weird)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mStrokeDasharrayLength) as usize - ptr as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(Weird), - "::", - stringify!(mStrokeDasharrayLength), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mClipRule) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(Weird), "::", stringify!(mClipRule)), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mColorInterpolation) as usize - ptr as usize - }, - 9usize, - concat!( - "Offset of field: ", - stringify!(Weird), - "::", - stringify!(mColorInterpolation), - ), - ); - assert_eq!( - unsafe { - ::std::ptr::addr_of!((*ptr).mColorInterpolationFilters) as usize - - ptr as usize - }, - 10usize, - concat!( - "Offset of field: ", - stringify!(Weird), - "::", - stringify!(mColorInterpolationFilters), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mFillRule) as usize - ptr as usize }, - 11usize, - concat!("Offset of field: ", stringify!(Weird), "::", stringify!(mFillRule)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mImageRendering) as usize - ptr as usize }, - 12usize, - concat!( - "Offset of field: ", - stringify!(Weird), - "::", - stringify!(mImageRendering), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mPaintOrder) as usize - ptr as usize }, - 13usize, - concat!("Offset of field: ", stringify!(Weird), "::", stringify!(mPaintOrder)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mShapeRendering) as usize - ptr as usize }, - 14usize, - concat!( - "Offset of field: ", - stringify!(Weird), - "::", - stringify!(mShapeRendering), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mStrokeLinecap) as usize - ptr as usize }, - 15usize, - concat!("Offset of field: ", stringify!(Weird), "::", stringify!(mStrokeLinecap)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mStrokeLinejoin) as usize - ptr as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(Weird), - "::", - stringify!(mStrokeLinejoin), - ), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mTextAnchor) as usize - ptr as usize }, - 17usize, - concat!("Offset of field: ", stringify!(Weird), "::", stringify!(mTextAnchor)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).mTextRendering) as usize - ptr as usize }, - 18usize, - concat!("Offset of field: ", stringify!(Weird), "::", stringify!(mTextRendering)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Weird"][::std::mem::size_of::() - 24usize]; + ["Alignment of Weird"][::std::mem::align_of::() - 4usize]; + [ + "Offset of field: Weird::mStrokeDasharrayLength", + ][::std::mem::offset_of!(Weird, mStrokeDasharrayLength) - 0usize]; + [ + "Offset of field: Weird::mClipRule", + ][::std::mem::offset_of!(Weird, mClipRule) - 8usize]; + [ + "Offset of field: Weird::mColorInterpolation", + ][::std::mem::offset_of!(Weird, mColorInterpolation) - 9usize]; + [ + "Offset of field: Weird::mColorInterpolationFilters", + ][::std::mem::offset_of!(Weird, mColorInterpolationFilters) - 10usize]; + [ + "Offset of field: Weird::mFillRule", + ][::std::mem::offset_of!(Weird, mFillRule) - 11usize]; + [ + "Offset of field: Weird::mImageRendering", + ][::std::mem::offset_of!(Weird, mImageRendering) - 12usize]; + [ + "Offset of field: Weird::mPaintOrder", + ][::std::mem::offset_of!(Weird, mPaintOrder) - 13usize]; + [ + "Offset of field: Weird::mShapeRendering", + ][::std::mem::offset_of!(Weird, mShapeRendering) - 14usize]; + [ + "Offset of field: Weird::mStrokeLinecap", + ][::std::mem::offset_of!(Weird, mStrokeLinecap) - 15usize]; + [ + "Offset of field: Weird::mStrokeLinejoin", + ][::std::mem::offset_of!(Weird, mStrokeLinejoin) - 16usize]; + [ + "Offset of field: Weird::mTextAnchor", + ][::std::mem::offset_of!(Weird, mTextAnchor) - 17usize]; + [ + "Offset of field: Weird::mTextRendering", + ][::std::mem::offset_of!(Weird, mTextRendering) - 18usize]; +}; impl Default for Weird { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::::uninit(); @@ -245,6 +236,31 @@ impl Weird { } } #[inline] + pub unsafe fn bitTest_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 0usize, 16u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bitTest_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] pub fn bitTest2(&self) -> ::std::os::raw::c_uint { unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 15u8) as u32) } } @@ -256,6 +272,31 @@ impl Weird { } } #[inline] + pub unsafe fn bitTest2_raw(this: *const Self) -> ::std::os::raw::c_uint { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_1), 16usize, 15u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_bitTest2_raw(this: *mut Self, val: ::std::os::raw::c_uint) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 4usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 15u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_1( bitTest: ::std::os::raw::c_uint, bitTest2: ::std::os::raw::c_uint, @@ -293,6 +334,34 @@ impl Weird { } } #[inline] + pub unsafe fn mFillOpacitySource_raw(this: *const Self) -> nsStyleSVGOpacitySource { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 0usize, 3u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_mFillOpacitySource_raw( + this: *mut Self, + val: nsStyleSVGOpacitySource, + ) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 0usize, + 3u8, + val as u64, + ) + } + } + #[inline] pub fn mStrokeOpacitySource(&self) -> nsStyleSVGOpacitySource { unsafe { ::std::mem::transmute(self._bitfield_2.get(3usize, 3u8) as u32) } } @@ -304,6 +373,36 @@ impl Weird { } } #[inline] + pub unsafe fn mStrokeOpacitySource_raw( + this: *const Self, + ) -> nsStyleSVGOpacitySource { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 3usize, 3u8) + as u32, + ) + } + } + #[inline] + pub unsafe fn set_mStrokeOpacitySource_raw( + this: *mut Self, + val: nsStyleSVGOpacitySource, + ) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 3usize, + 3u8, + val as u64, + ) + } + } + #[inline] pub fn mStrokeDasharrayFromObject(&self) -> bool { unsafe { ::std::mem::transmute(self._bitfield_2.get(6usize, 1u8) as u8) } } @@ -315,6 +414,30 @@ impl Weird { } } #[inline] + pub unsafe fn mStrokeDasharrayFromObject_raw(this: *const Self) -> bool { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 6usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_mStrokeDasharrayFromObject_raw(this: *mut Self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn mStrokeDashoffsetFromObject(&self) -> bool { unsafe { ::std::mem::transmute(self._bitfield_2.get(7usize, 1u8) as u8) } } @@ -326,6 +449,30 @@ impl Weird { } } #[inline] + pub unsafe fn mStrokeDashoffsetFromObject_raw(this: *const Self) -> bool { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 7usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_mStrokeDashoffsetFromObject_raw(this: *mut Self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn mStrokeWidthFromObject(&self) -> bool { unsafe { ::std::mem::transmute(self._bitfield_2.get(8usize, 1u8) as u8) } } @@ -337,6 +484,30 @@ impl Weird { } } #[inline] + pub unsafe fn mStrokeWidthFromObject_raw(this: *const Self) -> bool { + unsafe { + ::std::mem::transmute( + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_get(::std::ptr::addr_of!((*this)._bitfield_2), 8usize, 1u8) as u8, + ) + } + } + #[inline] + pub unsafe fn set_mStrokeWidthFromObject_raw(this: *mut Self, val: bool) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit< + [u8; 2usize], + >>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] pub fn new_bitfield_2( mFillOpacitySource: nsStyleSVGOpacitySource, mStrokeOpacitySource: nsStyleSVGOpacitySource, diff --git a/bindgen-tests/tests/expectations/tests/what_is_going_on.rs b/bindgen-tests/tests/expectations/tests/what_is_going_on.rs index 596636a961..aaeab668e1 100644 --- a/bindgen-tests/tests/expectations/tests/what_is_going_on.rs +++ b/bindgen-tests/tests/expectations/tests/what_is_going_on.rs @@ -4,26 +4,18 @@ pub struct UnknownUnits { pub _address: u8, } -#[test] -fn bindgen_test_layout_UnknownUnits() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(UnknownUnits)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(UnknownUnits)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of UnknownUnits"][::std::mem::size_of::() - 1usize]; + ["Alignment of UnknownUnits"][::std::mem::align_of::() - 1usize]; +}; pub type Float = f32; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct PointTyped { + pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, pub x: F, pub y: F, - pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell>, } impl Default for PointTyped { fn default() -> Self { diff --git a/bindgen-tests/tests/expectations/tests/win32-dtors.rs b/bindgen-tests/tests/expectations/tests/win32-dtors.rs index 8739ef4be8..042aa8cece 100644 --- a/bindgen-tests/tests/expectations/tests/win32-dtors.rs +++ b/bindgen-tests/tests/expectations/tests/win32-dtors.rs @@ -8,20 +8,12 @@ pub struct CppObj { fn bindgen_test_layout_CppObj() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 4usize, - concat!("Size of: ", stringify!(CppObj)), - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(CppObj)), - ); + assert_eq!(::std::mem::size_of::(), 4usize, "Size of CppObj"); + assert_eq!(::std::mem::align_of::(), 4usize, "Alignment of CppObj"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, 0usize, - concat!("Offset of field: ", stringify!(CppObj), "::", stringify!(x)), + "Offset of field: CppObj::x", ); } extern "C" { @@ -56,20 +48,12 @@ pub struct CppObj2 { fn bindgen_test_layout_CppObj2() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(CppObj2)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(CppObj2)), - ); + assert_eq!(::std::mem::size_of::(), 16usize, "Size of CppObj2"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of CppObj2"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, 8usize, - concat!("Offset of field: ", stringify!(CppObj2), "::", stringify!(x)), + "Offset of field: CppObj2::x", ); } extern "C" { @@ -107,20 +91,12 @@ pub struct CppObj3 { fn bindgen_test_layout_CppObj3() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(CppObj3)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(CppObj3)), - ); + assert_eq!(::std::mem::size_of::(), 24usize, "Size of CppObj3"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of CppObj3"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(CppObj3), "::", stringify!(x)), + "Offset of field: CppObj3::x", ); } extern "C" { @@ -158,20 +134,12 @@ pub struct CppObj4 { fn bindgen_test_layout_CppObj4() { const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(CppObj4)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(CppObj4)), - ); + assert_eq!(::std::mem::size_of::(), 24usize, "Size of CppObj4"); + assert_eq!(::std::mem::align_of::(), 8usize, "Alignment of CppObj4"); assert_eq!( unsafe { ::std::ptr::addr_of!((*ptr).x) as usize - ptr as usize }, 16usize, - concat!("Offset of field: ", stringify!(CppObj4), "::", stringify!(x)), + "Offset of field: CppObj4::x", ); } extern "C" { diff --git a/bindgen-tests/tests/expectations/tests/win32-thiscall.rs b/bindgen-tests/tests/expectations/tests/win32-thiscall.rs new file mode 100644 index 0000000000..d50348e799 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/win32-thiscall.rs @@ -0,0 +1,11 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone)] +pub struct Foo { + pub _address: u8, +} +#[test] +fn bindgen_test_layout_Foo() { + assert_eq!(::std::mem::size_of::(), 1usize, "Size of Foo"); + assert_eq!(::std::mem::align_of::(), 1usize, "Alignment of Foo"); +} diff --git a/bindgen-tests/tests/expectations/tests/win32-thiscall_1_0.rs b/bindgen-tests/tests/expectations/tests/win32-thiscall_1_0.rs deleted file mode 100644 index dc19e05dde..0000000000 --- a/bindgen-tests/tests/expectations/tests/win32-thiscall_1_0.rs +++ /dev/null @@ -1,24 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -#[derive(Debug, Default, Copy)] -pub struct Foo { - pub _address: u8, -} -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -impl Clone for Foo { - fn clone(&self) -> Self { - *self - } -} diff --git a/bindgen-tests/tests/expectations/tests/win32-thiscall_1_73.rs b/bindgen-tests/tests/expectations/tests/win32-thiscall_1_73.rs index 2faedf1814..4741f029ff 100644 --- a/bindgen-tests/tests/expectations/tests/win32-thiscall_1_73.rs +++ b/bindgen-tests/tests/expectations/tests/win32-thiscall_1_73.rs @@ -7,16 +7,8 @@ pub struct Foo { } #[test] fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); + assert_eq!(::std::mem::size_of::(), 1usize, "Size of Foo"); + assert_eq!(::std::mem::align_of::(), 1usize, "Alignment of Foo"); } extern "thiscall" { #[link_name = "\u{1}?test@Foo@@QAEXXZ"] diff --git a/bindgen-tests/tests/expectations/tests/win32-thiscall_nightly.rs b/bindgen-tests/tests/expectations/tests/win32-thiscall_nightly.rs index ba861131b9..87b63574a9 100644 --- a/bindgen-tests/tests/expectations/tests/win32-thiscall_nightly.rs +++ b/bindgen-tests/tests/expectations/tests/win32-thiscall_nightly.rs @@ -6,24 +6,16 @@ pub struct Foo { pub _address: u8, } -#[test] -fn bindgen_test_layout_Foo() { - assert_eq!( - ::std::mem::size_of::(), - 1usize, - concat!("Size of: ", stringify!(Foo)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(Foo)), - ); -} -extern "thiscall" { +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of Foo"][::std::mem::size_of::() - 1usize]; + ["Alignment of Foo"][::std::mem::align_of::() - 1usize]; +}; +unsafe extern "thiscall" { #[link_name = "\u{1}?test@Foo@@QAEXXZ"] pub fn Foo_test(this: *mut Foo); } -extern "thiscall" { +unsafe extern "thiscall" { #[link_name = "\u{1}?test2@Foo@@QAEHH@Z"] pub fn Foo_test2( this: *mut Foo, diff --git a/bindgen-tests/tests/expectations/tests/win32-vectorcall-nightly.rs b/bindgen-tests/tests/expectations/tests/win32-vectorcall-nightly.rs index a262b78c59..1c7b2fdbf6 100644 --- a/bindgen-tests/tests/expectations/tests/win32-vectorcall-nightly.rs +++ b/bindgen-tests/tests/expectations/tests/win32-vectorcall-nightly.rs @@ -1,7 +1,7 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #![cfg(feature = "nightly")] #![feature(abi_vectorcall)] -extern "vectorcall" { +unsafe extern "vectorcall" { #[link_name = "\u{1}test_vectorcall@@16"] pub fn test_vectorcall( a: ::std::os::raw::c_int, diff --git a/bindgen-tests/tests/expectations/tests/win32-vectorcall.rs b/bindgen-tests/tests/expectations/tests/win32-vectorcall.rs new file mode 100644 index 0000000000..fe64295a68 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/win32-vectorcall.rs @@ -0,0 +1 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] \ No newline at end of file diff --git a/bindgen-tests/tests/expectations/tests/with_array_pointers_arguments.rs b/bindgen-tests/tests/expectations/tests/with_array_pointers_arguments.rs index cc82fd4daf..7cc1d65daf 100644 --- a/bindgen-tests/tests/expectations/tests/with_array_pointers_arguments.rs +++ b/bindgen-tests/tests/expectations/tests/with_array_pointers_arguments.rs @@ -1,11 +1,11 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn test_fn( a: f32, arr: *mut [::std::os::raw::c_int; 20usize], ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { pub fn test_fn2( arr: *const [f32; 20usize], b: ::std::os::raw::c_int, @@ -13,6 +13,6 @@ extern "C" { } pub type defArr = [::std::os::raw::c_char; 20usize]; pub type foo = ::std::option::Option; -extern "C" { +unsafe extern "C" { pub fn bar(a: *mut defArr); } diff --git a/bindgen-tests/tests/expectations/tests/without_array_pointers_arguments.rs b/bindgen-tests/tests/expectations/tests/without_array_pointers_arguments.rs index f48e5f7f5c..d642e84d27 100644 --- a/bindgen-tests/tests/expectations/tests/without_array_pointers_arguments.rs +++ b/bindgen-tests/tests/expectations/tests/without_array_pointers_arguments.rs @@ -1,14 +1,14 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { pub fn test_fn(a: f32, arr: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { pub fn test_fn2(arr: *const f32, b: ::std::os::raw::c_int) -> ::std::os::raw::c_int; } pub type defArr = [::std::os::raw::c_char; 20usize]; pub type foo = ::std::option::Option< unsafe extern "C" fn(a: *mut ::std::os::raw::c_char), >; -extern "C" { +unsafe extern "C" { pub fn bar(a: *mut ::std::os::raw::c_char); } diff --git a/bindgen-tests/tests/expectations/tests/wrap-static-fns.rs b/bindgen-tests/tests/expectations/tests/wrap-static-fns.rs index 46b369b2f4..bafcad8a7e 100644 --- a/bindgen-tests/tests/expectations/tests/wrap-static-fns.rs +++ b/bindgen-tests/tests/expectations/tests/wrap-static-fns.rs @@ -1,17 +1,17 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern "C" { +unsafe extern "C" { #[link_name = "foo__extern"] pub fn foo() -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "bar__extern"] pub fn bar() -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "takes_ptr__extern"] pub fn takes_ptr(arg: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "takes_fn_ptr__extern"] pub fn takes_fn_ptr( f: ::std::option::Option< @@ -19,7 +19,7 @@ extern "C" { >, ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "takes_fn__extern"] pub fn takes_fn( f: ::std::option::Option< @@ -30,11 +30,11 @@ extern "C" { pub type func = ::std::option::Option< unsafe extern "C" fn(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int, >; -extern "C" { +unsafe extern "C" { #[link_name = "takes_alias__extern"] pub fn takes_alias(f: func) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "takes_qualified__extern"] pub fn takes_qualified( arg: *const *const ::std::os::raw::c_int, @@ -42,25 +42,25 @@ extern "C" { } pub const foo_BAR: foo = 0; pub type foo = ::std::os::raw::c_uint; -extern "C" { +unsafe extern "C" { #[link_name = "takes_enum__extern"] pub fn takes_enum(f: foo) -> foo; } -extern "C" { +unsafe extern "C" { #[link_name = "nevermore__extern"] pub fn nevermore(); } -extern "C" { +unsafe extern "C" { #[link_name = "takes_fn_with_no_args__extern"] pub fn takes_fn_with_no_args( f: ::std::option::Option ::std::os::raw::c_int>, ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "no_extra_argument__extern"] pub fn no_extra_argument(va: *mut __va_list_tag); } -extern "C" { +unsafe extern "C" { #[link_name = "many_va_list__extern"] pub fn many_va_list( i: ::std::os::raw::c_int, @@ -68,14 +68,14 @@ extern "C" { va2: *mut __va_list_tag, ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "wrap_as_variadic_fn1__extern"] pub fn wrap_as_variadic_fn1_wrapped( i: ::std::os::raw::c_int, ... ) -> ::std::os::raw::c_int; } -extern "C" { +unsafe extern "C" { #[link_name = "wrap_as_variadic_fn2__extern"] pub fn wrap_as_variadic_fn2_wrapped(i: ::std::os::raw::c_int, ...); } diff --git a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_anon_union.rs b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_anon_union.rs new file mode 100644 index 0000000000..50cefed043 --- /dev/null +++ b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_anon_union.rs @@ -0,0 +1,57 @@ +#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] +#[repr(C)] +pub struct TErrorResult { + pub mResult: ::std::os::raw::c_int, + pub __bindgen_anon_1: TErrorResult__bindgen_ty_1, + pub mMightHaveUnreported: bool, + pub mUnionState: TErrorResult_UnionState, +} +pub const TErrorResult_UnionState_HasMessage: TErrorResult_UnionState = 0; +pub const TErrorResult_UnionState_HasException: TErrorResult_UnionState = 0; +pub type TErrorResult_UnionState = i32; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct TErrorResult_Message { + _unused: [u8; 0], +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct TErrorResult_DOMExceptionInfo { + _unused: [u8; 0], +} +#[repr(C)] +pub union TErrorResult__bindgen_ty_1 { + pub mMessage: *mut TErrorResult_Message, + pub mDOMExceptionInfo: *mut TErrorResult_DOMExceptionInfo, +} +impl Default for TErrorResult__bindgen_ty_1 { + fn default() -> Self { + unsafe { + let mut s: Self = ::std::mem::uninitialized(); + ::std::ptr::write_bytes(&mut s, 0, 1); + s + } + } +} +impl Default for TErrorResult { + fn default() -> Self { + unsafe { + let mut s: Self = ::std::mem::uninitialized(); + ::std::ptr::write_bytes(&mut s, 0, 1); + s + } + } +} +#[repr(C)] +pub struct ErrorResult { + pub _base: TErrorResult, +} +impl Default for ErrorResult { + fn default() -> Self { + unsafe { + let mut s: Self = ::std::mem::uninitialized(); + ::std::ptr::write_bytes(&mut s, 0, 1); + s + } + } +} diff --git a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_anon_union_1_0.rs b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_anon_union_1_0.rs deleted file mode 100644 index dfe2213ed4..0000000000 --- a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_anon_union_1_0.rs +++ /dev/null @@ -1,100 +0,0 @@ -#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -#[repr(C)] -pub struct __BindgenUnionField(::std::marker::PhantomData); -impl __BindgenUnionField { - #[inline] - pub fn new() -> Self { - __BindgenUnionField(::std::marker::PhantomData) - } - #[inline] - pub unsafe fn as_ref(&self) -> &T { - unsafe { ::std::mem::transmute(self) } - } - #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { - unsafe { ::std::mem::transmute(self) } - } -} -impl ::std::default::Default for __BindgenUnionField { - #[inline] - fn default() -> Self { - Self::new() - } -} -impl ::std::clone::Clone for __BindgenUnionField { - #[inline] - fn clone(&self) -> Self { - *self - } -} -impl ::std::marker::Copy for __BindgenUnionField {} -impl ::std::fmt::Debug for __BindgenUnionField { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - fmt.write_str("__BindgenUnionField") - } -} -impl ::std::hash::Hash for __BindgenUnionField { - fn hash(&self, _state: &mut H) {} -} -impl ::std::cmp::PartialEq for __BindgenUnionField { - fn eq(&self, _other: &__BindgenUnionField) -> bool { - true - } -} -impl ::std::cmp::Eq for __BindgenUnionField {} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct TErrorResult { - pub mResult: ::std::os::raw::c_int, - pub __bindgen_anon_1: TErrorResult__bindgen_ty_1, - pub mMightHaveUnreported: bool, - pub mUnionState: TErrorResult_UnionState, -} -pub const TErrorResult_UnionState_HasMessage: TErrorResult_UnionState = 0; -pub const TErrorResult_UnionState_HasException: TErrorResult_UnionState = 0; -pub type TErrorResult_UnionState = i32; -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct TErrorResult_Message { - _unused: [u8; 0], -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct TErrorResult_DOMExceptionInfo { - _unused: [u8; 0], -} -#[repr(C)] -#[derive(Debug, Default, Copy, Clone)] -pub struct TErrorResult__bindgen_ty_1 { - pub mMessage: __BindgenUnionField<*mut TErrorResult_Message>, - pub mDOMExceptionInfo: __BindgenUnionField<*mut TErrorResult_DOMExceptionInfo>, - pub bindgen_union_field: u64, -} -impl Default for TErrorResult { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} -#[repr(C)] -#[derive(Debug, Copy)] -pub struct ErrorResult { - pub _base: TErrorResult, -} -impl Clone for ErrorResult { - fn clone(&self) -> Self { - *self - } -} -impl Default for ErrorResult { - fn default() -> Self { - unsafe { - let mut s: Self = ::std::mem::uninitialized(); - ::std::ptr::write_bytes(&mut s, 0, 1); - s - } - } -} diff --git a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_class.rs b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_class.rs index 5f64396f6b..617a037631 100644 --- a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_class.rs +++ b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_class.rs @@ -166,26 +166,26 @@ impl Default for WithUnion { pub struct RealAbstractionWithTonsOfMethods { pub _address: u8, } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZNK32RealAbstractionWithTonsOfMethods3barEv"] pub fn RealAbstractionWithTonsOfMethods_bar( this: *const RealAbstractionWithTonsOfMethods, ); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN32RealAbstractionWithTonsOfMethods3barEv"] pub fn RealAbstractionWithTonsOfMethods_bar1( this: *mut RealAbstractionWithTonsOfMethods, ); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN32RealAbstractionWithTonsOfMethods3barEi"] pub fn RealAbstractionWithTonsOfMethods_bar2( this: *mut RealAbstractionWithTonsOfMethods, foo: ::std::os::raw::c_int, ); } -extern "C" { +unsafe extern "C" { #[link_name = "\u{1}_ZN32RealAbstractionWithTonsOfMethods3staEv"] pub fn RealAbstractionWithTonsOfMethods_sta(); } diff --git a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_dynamic_loading_simple.rs b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_dynamic_loading_simple.rs index 968f10f6e5..05be5d9944 100644 --- a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_dynamic_loading_simple.rs +++ b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_dynamic_loading_simple.rs @@ -1,5 +1,4 @@ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] -extern crate libloading; pub struct TestLib { __library: ::libloading::Library, pub foo: Result< @@ -17,13 +16,14 @@ pub struct TestLib { unsafe extern "C" fn() -> ::std::os::raw::c_int, ::libloading::Error, >, + pub FLUX: Result<*mut ::std::os::raw::c_int, ::libloading::Error>, } impl TestLib { pub unsafe fn new

(path: P) -> Result where P: AsRef<::std::ffi::OsStr>, { - let library = ::libloading::Library::new(path)?; + let library = unsafe { ::libloading::Library::new(path) }?; unsafe { Self::from_library(library) } } pub unsafe fn from_library(library: L) -> Result @@ -34,11 +34,14 @@ impl TestLib { let foo = unsafe { __library.get(b"foo\0") }.map(|sym| *sym); let bar = unsafe { __library.get(b"bar\0") }.map(|sym| *sym); let baz = unsafe { __library.get(b"baz\0") }.map(|sym| *sym); + let FLUX = unsafe { __library.get::<*mut ::std::os::raw::c_int>(b"FLUX\0") } + .map(|sym| *sym); Ok(TestLib { __library, foo, bar, baz, + FLUX, }) } pub unsafe fn foo( @@ -54,4 +57,7 @@ impl TestLib { pub unsafe fn baz(&self) -> ::std::os::raw::c_int { unsafe { (self.baz.as_ref().expect("Expected function, got error."))() } } + pub unsafe fn FLUX(&self) -> *mut ::std::os::raw::c_int { + *self.FLUX.as_ref().expect("Expected variable, got error.") + } } diff --git a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_objc_class.rs b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_objc_class.rs index c8f7241fcf..34252b10d3 100644 --- a/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_objc_class.rs +++ b/bindgen-tests/tests/expectations/tests/wrap_unsafe_ops_objc_class.rs @@ -3,7 +3,7 @@ use objc::{self, msg_send, sel, sel_impl, class}; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; -extern "C" { +unsafe extern "C" { pub static mut fooVar: Foo; } #[repr(transparent)] diff --git a/bindgen-tests/tests/expectations/tests/zero-size-array-align.rs b/bindgen-tests/tests/expectations/tests/zero-size-array-align.rs index be373d7ae8..48fc0cb1d6 100644 --- a/bindgen-tests/tests/expectations/tests/zero-size-array-align.rs +++ b/bindgen-tests/tests/expectations/tests/zero-size-array-align.rs @@ -36,33 +36,15 @@ pub struct dm_deps { pub filler: ::std::os::raw::c_uint, pub device: __IncompleteArrayField<::std::os::raw::c_ulonglong>, } -#[test] -fn bindgen_test_layout_dm_deps() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 8usize, - concat!("Size of: ", stringify!(dm_deps)), - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(dm_deps)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).count) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(dm_deps), "::", stringify!(count)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).filler) as usize - ptr as usize }, - 4usize, - concat!("Offset of field: ", stringify!(dm_deps), "::", stringify!(filler)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).device) as usize - ptr as usize }, - 8usize, - concat!("Offset of field: ", stringify!(dm_deps), "::", stringify!(device)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of dm_deps"][::std::mem::size_of::() - 8usize]; + ["Alignment of dm_deps"][::std::mem::align_of::() - 8usize]; + ["Offset of field: dm_deps::count"][::std::mem::offset_of!(dm_deps, count) - 0usize]; + [ + "Offset of field: dm_deps::filler", + ][::std::mem::offset_of!(dm_deps, filler) - 4usize]; + [ + "Offset of field: dm_deps::device", + ][::std::mem::offset_of!(dm_deps, device) - 8usize]; +}; diff --git a/bindgen-tests/tests/expectations/tests/zero-sized-array.rs b/bindgen-tests/tests/expectations/tests/zero-sized-array.rs index bc4b660029..229a6ee4db 100644 --- a/bindgen-tests/tests/expectations/tests/zero-sized-array.rs +++ b/bindgen-tests/tests/expectations/tests/zero-sized-array.rs @@ -35,57 +35,32 @@ impl ::std::fmt::Debug for __IncompleteArrayField { pub struct ZeroSizedArray { pub arr: __IncompleteArrayField<::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_ZeroSizedArray() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(ZeroSizedArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ZeroSizedArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arr) as usize - ptr as usize }, - 0usize, - concat!("Offset of field: ", stringify!(ZeroSizedArray), "::", stringify!(arr)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + ["Size of ZeroSizedArray"][::std::mem::size_of::() - 0usize]; + ["Alignment of ZeroSizedArray"][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ZeroSizedArray::arr", + ][::std::mem::offset_of!(ZeroSizedArray, arr) - 0usize]; +}; /// And nor should this get an `_address` field. #[repr(C)] #[derive(Debug, Default)] pub struct ContainsZeroSizedArray { pub zsa: ZeroSizedArray, } -#[test] -fn bindgen_test_layout_ContainsZeroSizedArray() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(ContainsZeroSizedArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ContainsZeroSizedArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).zsa) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContainsZeroSizedArray), - "::", - stringify!(zsa), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ContainsZeroSizedArray", + ][::std::mem::size_of::() - 0usize]; + [ + "Alignment of ContainsZeroSizedArray", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ContainsZeroSizedArray::zsa", + ][::std::mem::offset_of!(ContainsZeroSizedArray, zsa) - 0usize]; +}; /** Inheriting from ZeroSizedArray shouldn't cause an `_address` to be inserted either.*/ #[repr(C)] @@ -93,78 +68,48 @@ fn bindgen_test_layout_ContainsZeroSizedArray() { pub struct InheritsZeroSizedArray { pub _base: ZeroSizedArray, } -#[test] -fn bindgen_test_layout_InheritsZeroSizedArray() { - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(InheritsZeroSizedArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(InheritsZeroSizedArray)), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of InheritsZeroSizedArray", + ][::std::mem::size_of::() - 0usize]; + [ + "Alignment of InheritsZeroSizedArray", + ][::std::mem::align_of::() - 1usize]; +}; /// And this should not get an `_address` field either. #[repr(C)] #[derive(Debug, Default)] pub struct DynamicallySizedArray { pub arr: __IncompleteArrayField<::std::os::raw::c_char>, } -#[test] -fn bindgen_test_layout_DynamicallySizedArray() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(DynamicallySizedArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(DynamicallySizedArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).arr) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(DynamicallySizedArray), - "::", - stringify!(arr), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of DynamicallySizedArray", + ][::std::mem::size_of::() - 0usize]; + [ + "Alignment of DynamicallySizedArray", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: DynamicallySizedArray::arr", + ][::std::mem::offset_of!(DynamicallySizedArray, arr) - 0usize]; +}; /// No `_address` field here either. #[repr(C)] #[derive(Debug, Default)] pub struct ContainsDynamicallySizedArray { pub dsa: DynamicallySizedArray, } -#[test] -fn bindgen_test_layout_ContainsDynamicallySizedArray() { - const UNINIT: ::std::mem::MaybeUninit = ::std::mem::MaybeUninit::uninit(); - let ptr = UNINIT.as_ptr(); - assert_eq!( - ::std::mem::size_of::(), - 0usize, - concat!("Size of: ", stringify!(ContainsDynamicallySizedArray)), - ); - assert_eq!( - ::std::mem::align_of::(), - 1usize, - concat!("Alignment of ", stringify!(ContainsDynamicallySizedArray)), - ); - assert_eq!( - unsafe { ::std::ptr::addr_of!((*ptr).dsa) as usize - ptr as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(ContainsDynamicallySizedArray), - "::", - stringify!(dsa), - ), - ); -} +#[allow(clippy::unnecessary_operation, clippy::identity_op)] +const _: () = { + [ + "Size of ContainsDynamicallySizedArray", + ][::std::mem::size_of::() - 0usize]; + [ + "Alignment of ContainsDynamicallySizedArray", + ][::std::mem::align_of::() - 1usize]; + [ + "Offset of field: ContainsDynamicallySizedArray::dsa", + ][::std::mem::offset_of!(ContainsDynamicallySizedArray, dsa) - 0usize]; +}; diff --git a/bindgen-tests/tests/headers/16-byte-alignment_1_0.h b/bindgen-tests/tests/headers/16-byte-alignment_1_0.h deleted file mode 100644 index 8a9fd4910e..0000000000 --- a/bindgen-tests/tests/headers/16-byte-alignment_1_0.h +++ /dev/null @@ -1,34 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; - -struct rte_ipv4_tuple { - uint32_t src_addr; - uint32_t dst_addr; - union { - struct { - uint16_t dport; - uint16_t sport; - }; - uint32_t sctp_tag; - }; -}; - -struct rte_ipv6_tuple { - uint8_t src_addr[16]; - uint8_t dst_addr[16]; - union { - struct { - uint16_t dport; - uint16_t sport; - }; - uint32_t sctp_tag; - }; -}; - -union rte_thash_tuple { - struct rte_ipv4_tuple v4; - struct rte_ipv6_tuple v6; -} __attribute__((aligned(16))); diff --git a/bindgen-tests/tests/headers/abi-override.h b/bindgen-tests/tests/headers/abi-override.h index 578659733e..0b0fdcf245 100644 --- a/bindgen-tests/tests/headers/abi-override.h +++ b/bindgen-tests/tests/headers/abi-override.h @@ -1,4 +1,4 @@ -// bindgen-flags: --override-abi=foo=fastcall --override-abi=bar=stdcall --override-abi=boo=efiapi --override-abi=foobar=efiapi --override-abi qux=system +// bindgen-flags: --override-abi=foo=fastcall --override-abi=bar=stdcall --override-abi=boo=efiapi --override-abi=foobar=efiapi --override-abi qux=system --raw-line '#![cfg(target = "i686-pc-windows-msvc")]' void foo(); void bar(); diff --git a/bindgen-tests/tests/headers/anon_enum_allowlist_item.h b/bindgen-tests/tests/headers/anon_enum_allowlist_item.h new file mode 100644 index 0000000000..23caacc9a1 --- /dev/null +++ b/bindgen-tests/tests/headers/anon_enum_allowlist_item.h @@ -0,0 +1,6 @@ +// bindgen-flags: --allowlist-item "NODE_.*" + +enum { + NODE_FLAG_FOO, + NODE_FLAG_BAR, +}; diff --git a/bindgen-tests/tests/headers/anon_enum_blocklist.h b/bindgen-tests/tests/headers/anon_enum_blocklist.h new file mode 100644 index 0000000000..61aa6e680c --- /dev/null +++ b/bindgen-tests/tests/headers/anon_enum_blocklist.h @@ -0,0 +1,11 @@ +// bindgen-flags: --blocklist-type "_bindgen_ty_1" + +enum { + FLAG_X, + FLAG_Y, +}; + +enum { + FLAG_Z, + FLAG_W, +}; diff --git a/bindgen-tests/tests/headers/anon_struct_in_union_1_0.h b/bindgen-tests/tests/headers/anon_struct_in_union_1_0.h deleted file mode 100644 index 6b59723a3c..0000000000 --- a/bindgen-tests/tests/headers/anon_struct_in_union_1_0.h +++ /dev/null @@ -1,9 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -struct s { - union { - struct inner { - int b; - } field; - } u; -}; diff --git a/bindgen-tests/tests/headers/anon_union_1_0.hpp b/bindgen-tests/tests/headers/anon_union_1_0.hpp deleted file mode 100644 index 3d9ae3dde9..0000000000 --- a/bindgen-tests/tests/headers/anon_union_1_0.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq --rustified-enum ".*" - -template -struct TErrorResult { - enum UnionState { - HasMessage, - HasException, - }; - int mResult; - struct Message; - struct DOMExceptionInfo; - union { - Message* mMessage; - DOMExceptionInfo* mDOMExceptionInfo; - }; - - bool mMightHaveUnreported; - UnionState mUnionState; -}; - -struct ErrorResult : public TErrorResult { -}; diff --git a/bindgen-tests/tests/headers/atomic-constant.h b/bindgen-tests/tests/headers/atomic-constant.h new file mode 100644 index 0000000000..b28f76f7e4 --- /dev/null +++ b/bindgen-tests/tests/headers/atomic-constant.h @@ -0,0 +1,2 @@ +_Atomic(int) a; +int b; diff --git a/bindgen-tests/tests/headers/attribute-custom-cli.h b/bindgen-tests/tests/headers/attribute-custom-cli.h new file mode 100644 index 0000000000..a5f73c78e5 --- /dev/null +++ b/bindgen-tests/tests/headers/attribute-custom-cli.h @@ -0,0 +1,14 @@ +// bindgen-flags: --default-enum-style rust --default-non-copy-union-style manually_drop --no-default=".*" --no-hash=".*" --no-partialeq=".*" --no-debug=".*" --no-copy=".*" --with-attribute-custom="foo_[^e].*=#[doc(hidden)]" --with-attribute-custom-struct="foo.*=#[derive(Default)]" --with-attribute-custom-enum="foo.*=#[cfg_attr(test, derive(PartialOrd, Copy))]" --with-attribute-custom-union="foo.*=#[derive(Clone)],#[derive(Copy)]" +struct foo_struct { + int inner; +}; +enum foo_enum { + inner = 0 +}; +union foo_union { + int fst; + float snd; +}; +struct non_matching { + int inner; +}; diff --git a/bindgen-tests/tests/headers/attribute-custom.h b/bindgen-tests/tests/headers/attribute-custom.h new file mode 100644 index 0000000000..dd382bf8cd --- /dev/null +++ b/bindgen-tests/tests/headers/attribute-custom.h @@ -0,0 +1,28 @@ +// bindgen-flags: --no-derive-debug --no-derive-copy --no-derive-default --default-enum-style rust --no-layout-tests + +/**

*/ +struct my_type; + +/**
*/ +struct my_type; + +struct my_type { + int a; +}; + +/** + *
+ *
+ */ +struct my_type2; + +struct my_type2 { + unsigned a; +}; + +/** + *
+ */ +struct my_type3 { + unsigned long a; +}; diff --git a/bindgen-tests/tests/headers/attribute_warn_unused_result.hpp b/bindgen-tests/tests/headers/attribute_warn_unused_result.hpp index 26fda0910c..258b6396de 100644 --- a/bindgen-tests/tests/headers/attribute_warn_unused_result.hpp +++ b/bindgen-tests/tests/headers/attribute_warn_unused_result.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.27 --enable-function-attribute-detection +// bindgen-flags: \-\-rust-target=1.33 --enable-function-attribute-detection class Foo { public: diff --git a/bindgen-tests/tests/headers/attribute_warn_unused_result_no_attribute_detection.hpp b/bindgen-tests/tests/headers/attribute_warn_unused_result_no_attribute_detection.hpp index 2155030711..a102cbf100 100644 --- a/bindgen-tests/tests/headers/attribute_warn_unused_result_no_attribute_detection.hpp +++ b/bindgen-tests/tests/headers/attribute_warn_unused_result_no_attribute_detection.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.27 +// bindgen-flags: \-\-rust-target=1.33 class Foo { public: diff --git a/bindgen-tests/tests/headers/attribute_warn_unused_result_pre_1_27.hpp b/bindgen-tests/tests/headers/attribute_warn_unused_result_pre_1_27.hpp deleted file mode 100644 index 25127d9cd0..0000000000 --- a/bindgen-tests/tests/headers/attribute_warn_unused_result_pre_1_27.hpp +++ /dev/null @@ -1,8 +0,0 @@ -class Foo { -public: - __attribute__((warn_unused_result)) - int foo(int); -}; - -__attribute__((warn_unused_result)) -int foo(int); diff --git a/bindgen-tests/tests/headers/bindgen-union-inside-namespace.hpp b/bindgen-tests/tests/headers/bindgen-union-inside-namespace.hpp index 6a7d3a300c..78b05b4f92 100644 --- a/bindgen-tests/tests/headers/bindgen-union-inside-namespace.hpp +++ b/bindgen-tests/tests/headers/bindgen-union-inside-namespace.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.0 --enable-cxx-namespaces +// bindgen-flags: \-\-rust-target=1.33 --enable-cxx-namespaces namespace foo { union Bar { diff --git a/bindgen-tests/tests/headers/bitfield-enum-repr-c.hpp b/bindgen-tests/tests/headers/bitfield-enum-repr-c.hpp index 20a3f9dbbe..b80f5d99a5 100644 --- a/bindgen-tests/tests/headers/bitfield-enum-repr-c.hpp +++ b/bindgen-tests/tests/headers/bitfield-enum-repr-c.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --bitfield-enum "Foo" --rust-target 1.27 -- -std=c++11 +// bindgen-flags: --bitfield-enum "Foo" \-\-rust-target=1.33 -- -std=c++11 enum Foo { Bar = 1 << 1, diff --git a/bindgen-tests/tests/headers/bitfield-enum-repr-transparent.hpp b/bindgen-tests/tests/headers/bitfield-enum-repr-transparent.hpp index e53bb0753c..b80f5d99a5 100644 --- a/bindgen-tests/tests/headers/bitfield-enum-repr-transparent.hpp +++ b/bindgen-tests/tests/headers/bitfield-enum-repr-transparent.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --bitfield-enum "Foo" --rust-target 1.28 -- -std=c++11 +// bindgen-flags: --bitfield-enum "Foo" \-\-rust-target=1.33 -- -std=c++11 enum Foo { Bar = 1 << 1, diff --git a/bindgen-tests/tests/headers/blocklist_bitfield_unit.h b/bindgen-tests/tests/headers/blocklist_bitfield_unit.h new file mode 100644 index 0000000000..5f7d94ced9 --- /dev/null +++ b/bindgen-tests/tests/headers/blocklist_bitfield_unit.h @@ -0,0 +1,7 @@ +// bindgen-flags: --blocklist-type "__BindgenBitfieldUnit" --raw-line '#[path = "./struct_with_bitfields.rs"] mod bitfields;' --raw-line 'use bitfields::*;' +struct C { + unsigned char x; + unsigned b1 : 1; + unsigned b2 : 1; + unsigned baz; +}; diff --git a/bindgen-tests/tests/headers/char16_t.hpp b/bindgen-tests/tests/headers/char16_t.hpp new file mode 100644 index 0000000000..35e1f16dd3 --- /dev/null +++ b/bindgen-tests/tests/headers/char16_t.hpp @@ -0,0 +1,4 @@ +// bindgen-flags: --use-distinct-char16-t --raw-line '#[repr(transparent)] pub struct bindgen_cchar16_t(u16);' -- -x c++ -std=c++14 + +void receive_char16_t(char16_t input) { +} diff --git a/bindgen-tests/tests/headers/class_1_0.hpp b/bindgen-tests/tests/headers/class_1_0.hpp deleted file mode 100644 index e3735eb68d..0000000000 --- a/bindgen-tests/tests/headers/class_1_0.hpp +++ /dev/null @@ -1,76 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --impl-partialeq --with-derive-eq - -class C { - int a; - // More than rust limits (32) - char big_array[33]; -}; - -class C_with_zero_length_array { - int a; - // More than rust limits (32) - char big_array[33]; - char zero_length_array[0]; -}; - -class C_with_zero_length_array_2 { - int a; - char zero_length_array[0]; -}; - -class C_with_incomplete_array { - int a; - // More than rust limits (32) - char big_array[33]; - char incomplete_array[]; -}; - -class C_with_incomplete_array_2 { - int a; - char incomplete_array[]; -}; - - -class C_with_zero_length_array_and_incomplete_array { - int a; - // More than rust limits (32) - char big_array[33]; - char zero_length_array[0]; - char incomplete_array[]; -}; - -class C_with_zero_length_array_and_incomplete_array_2 { - int a; - char zero_length_array[0]; - char incomplete_array[]; -}; - - -class WithDtor { - int b; - - ~WithDtor() {} -}; - -class IncompleteArrayNonCopiable { - void* whatever; - C incomplete_array[]; -}; - -union Union { - float d; - int i; -}; - -class WithUnion { - Union data; -}; - -class RealAbstractionWithTonsOfMethods { - void foo(); -public: - void bar() const; - void bar(); - void bar(int foo); - static void sta(); -}; diff --git a/bindgen-tests/tests/headers/class_with_enum.hpp b/bindgen-tests/tests/headers/class_with_enum.hpp new file mode 100644 index 0000000000..ebbc2c4049 --- /dev/null +++ b/bindgen-tests/tests/headers/class_with_enum.hpp @@ -0,0 +1,7 @@ +class A { +public: + enum B { + B1, + B2, + }; +}; \ No newline at end of file diff --git a/bindgen-tests/tests/headers/class_with_inner_struct_1_0.hpp b/bindgen-tests/tests/headers/class_with_inner_struct_1_0.hpp deleted file mode 100644 index 34ed96e722..0000000000 --- a/bindgen-tests/tests/headers/class_with_inner_struct_1_0.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq --rustified-enum ".*" -// bindgen-flags: -- -std=c++11 - -class A { - unsigned c; - struct Segment { int begin, end; }; - union { - int f; - } named_union; - union { - int d; - }; -}; - -class B { - unsigned d; - struct Segment { int begin, end; }; -}; - - -enum class StepSyntax { - Keyword, // step-start and step-end - FunctionalWithoutKeyword, // steps(...) - FunctionalWithStartKeyword, // steps(..., start) - FunctionalWithEndKeyword, // steps(..., end) -}; - -class C { - unsigned d; - union { - struct { - float mX1; - float mY1; - float mX2; - float mY2; - } mFunc; - struct { - StepSyntax mStepSyntax; - unsigned int mSteps; - }; - }; - // To ensure it doesn't collide - struct Segment { int begin, end; }; -}; diff --git a/bindgen-tests/tests/headers/const_array_typedef.h b/bindgen-tests/tests/headers/const_array_typedef.h new file mode 100644 index 0000000000..e5379c97ba --- /dev/null +++ b/bindgen-tests/tests/headers/const_array_typedef.h @@ -0,0 +1,13 @@ +typedef struct { + int field; +} strct; + +typedef strct typ[1]; + +extern typ w; +extern strct *x; + +extern const typ y; +extern const strct *z; + +void function(const typ a, const strct *b); diff --git a/bindgen-tests/tests/headers/constructors.hpp b/bindgen-tests/tests/headers/constructors.hpp index d417488917..2f8d57b00b 100644 --- a/bindgen-tests/tests/headers/constructors.hpp +++ b/bindgen-tests/tests/headers/constructors.hpp @@ -1,6 +1,6 @@ class TestOverload { - // This one shouldnt' be generated. + // This one shouldn't be generated. TestOverload(); public: TestOverload(int); diff --git a/bindgen-tests/tests/headers/constructors_1_33.hpp b/bindgen-tests/tests/headers/constructors_1_33.hpp index 7c6262d417..e275f8907e 100644 --- a/bindgen-tests/tests/headers/constructors_1_33.hpp +++ b/bindgen-tests/tests/headers/constructors_1_33.hpp @@ -1,7 +1,7 @@ // bindgen-flags: --rust-target 1.33 class TestOverload { - // This one shouldnt' be generated. + // This one shouldn't be generated. TestOverload(); public: /// Calling this should use `mem::unintialized()` and not `MaybeUninit()` as only rust 1.36 includes that. diff --git a/bindgen-tests/tests/headers/derive-clone_1_0.h b/bindgen-tests/tests/headers/derive-clone_1_0.h deleted file mode 100644 index 34ef40ae97..0000000000 --- a/bindgen-tests/tests/headers/derive-clone_1_0.h +++ /dev/null @@ -1,7 +0,0 @@ -// bindgen-flags: --rust-target 1.0 - -/// Since builtin `Clone` impls were introduced in Rust 1.21 this struct -/// should impl `Clone` "manually". -struct ShouldImplClone { - int large[33]; -}; diff --git a/bindgen-tests/tests/headers/derive-debug-bitfield-1-51.hpp b/bindgen-tests/tests/headers/derive-debug-bitfield-1-51.hpp new file mode 100644 index 0000000000..a68611d98b --- /dev/null +++ b/bindgen-tests/tests/headers/derive-debug-bitfield-1-51.hpp @@ -0,0 +1,7 @@ +// bindgen-flags: --impl-debug --rust-target 1.51 + +class C { + bool a: 1; + bool b: 7; + int large_array[50]; +}; diff --git a/bindgen-tests/tests/headers/derive-partialeq-union_1_0.hpp b/bindgen-tests/tests/headers/derive-partialeq-union_1_0.hpp deleted file mode 100644 index d546d77b10..0000000000 --- a/bindgen-tests/tests/headers/derive-partialeq-union_1_0.hpp +++ /dev/null @@ -1,7 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-partialeq --impl-partialeq - -/// This should manually derive PartialEq. -union ShouldDerivePartialEq { - char a[150]; - int b; -}; diff --git a/bindgen-tests/tests/headers/dynamic_loading_variable_required.h b/bindgen-tests/tests/headers/dynamic_loading_variable_required.h new file mode 100644 index 0000000000..8e811bb320 --- /dev/null +++ b/bindgen-tests/tests/headers/dynamic_loading_variable_required.h @@ -0,0 +1,4 @@ +// bindgen-flags: --dynamic-loading TestLib --dynamic-link-require-all + +int foo; +int *baz; \ No newline at end of file diff --git a/bindgen-tests/tests/headers/dynamic_loading_variable_simple.h b/bindgen-tests/tests/headers/dynamic_loading_variable_simple.h new file mode 100644 index 0000000000..5ecad752ed --- /dev/null +++ b/bindgen-tests/tests/headers/dynamic_loading_variable_simple.h @@ -0,0 +1,4 @@ +// bindgen-flags: --dynamic-loading TestLib + +int foo; +int *baz; \ No newline at end of file diff --git a/bindgen-tests/tests/headers/dynamic_loading_variable_with_allowlist.hpp b/bindgen-tests/tests/headers/dynamic_loading_variable_with_allowlist.hpp new file mode 100644 index 0000000000..5e27303063 --- /dev/null +++ b/bindgen-tests/tests/headers/dynamic_loading_variable_with_allowlist.hpp @@ -0,0 +1,5 @@ +// bindgen-flags: --dynamic-loading TestLib --allowlist-var foo --allowlist-var bar + +int foo; +int bar; +int baz; // should not be allowed \ No newline at end of file diff --git a/bindgen-tests/tests/headers/enum-doc.h b/bindgen-tests/tests/headers/enum-doc.h index 58e2c69e13..7a2f425cda 100644 --- a/bindgen-tests/tests/headers/enum-doc.h +++ b/bindgen-tests/tests/headers/enum-doc.h @@ -2,14 +2,14 @@ enum B { /// Document field with three slashes VAR_A = 0, - /** Document field with preceeding star */ + /** Document field with preceding star */ VAR_B = 1, - /*! Document field with preceeding exclamation */ + /*! Document field with preceding exclamation */ VAR_C = 2, VAR_D = 3, /**< Document field with following star */ VAR_E = 4, /*!< Document field with following exclamation */ /** - * Document field with preceeding star, with a loong long multiline + * Document field with preceding star, with a loong long multiline * comment. * * Very interesting documentation, definitely. diff --git a/bindgen-tests/tests/headers/extern_blocks_post_1_82.h b/bindgen-tests/tests/headers/extern_blocks_post_1_82.h new file mode 100644 index 0000000000..f7f3464e98 --- /dev/null +++ b/bindgen-tests/tests/headers/extern_blocks_post_1_82.h @@ -0,0 +1,5 @@ +// bindgen-flags: --no-layout-tests --rust-target=1.82 + +void cool_function(int i, char c); + +static int cool_static; diff --git a/bindgen-tests/tests/headers/extern_blocks_pre_1_82.h b/bindgen-tests/tests/headers/extern_blocks_pre_1_82.h new file mode 100644 index 0000000000..abed05d11f --- /dev/null +++ b/bindgen-tests/tests/headers/extern_blocks_pre_1_82.h @@ -0,0 +1,5 @@ +// bindgen-flags: --no-layout-tests --rust-target=1.81 + +void cool_function(int i, char c); + +static int cool_static; diff --git a/bindgen-tests/tests/headers/flexarray.hpp b/bindgen-tests/tests/headers/flexarray.hpp new file mode 100644 index 0000000000..b698c38d19 --- /dev/null +++ b/bindgen-tests/tests/headers/flexarray.hpp @@ -0,0 +1,32 @@ +// bindgen-flags: --rust-target nightly --flexarray-dst --raw-line '#![cfg(feature = "nightly")]' --raw-line '#![feature(ptr_metadata, layout_for_ptr)]' + +struct flexarray { + int count; + int data[]; +}; + +struct flexarray_zero { + int count; + int data[0]; +}; + +template +struct flexarray_template { + int count; + T data[]; +}; + +struct flexarray_ref { + flexarray *things; +}; + +struct flexarray_bogus_zero_fam { + int count; + int data1[0]; + char data2[]; +}; + +struct flexarray_align { + int count; + int data[]; +} __attribute__((aligned(128))); diff --git a/bindgen-tests/tests/headers/forward_declared_complex_types_1_0.hpp b/bindgen-tests/tests/headers/forward_declared_complex_types_1_0.hpp deleted file mode 100644 index ff6076fc43..0000000000 --- a/bindgen-tests/tests/headers/forward_declared_complex_types_1_0.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// bindgen-flags: --rust-target 1.0 - -struct Foo_empty {}; -struct Foo; - -struct Bar { - Foo *f; -}; - -void baz_struct(Foo* f); - -union Union; - -void baz_union(Union* u); - -class Quux; - -void baz_class(Quux* q); diff --git a/bindgen-tests/tests/headers/i128.h b/bindgen-tests/tests/headers/i128.h index 6ec399c726..609d546190 100644 --- a/bindgen-tests/tests/headers/i128.h +++ b/bindgen-tests/tests/headers/i128.h @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.26 +// bindgen-flags: \-\-rust-target=1.33 struct foo { __int128 my_signed; diff --git a/bindgen-tests/tests/headers/inline_namespace_macro.hpp b/bindgen-tests/tests/headers/inline_namespace_macro.hpp new file mode 100644 index 0000000000..c7cf5caf98 --- /dev/null +++ b/bindgen-tests/tests/headers/inline_namespace_macro.hpp @@ -0,0 +1,9 @@ +// bindgen-flags: --enable-cxx-namespaces -- -std=c++11 + +#include "namespace/nsdefine.h" + +BEGIN_NAMESPACE + +class duration {}; + +END_NAMESPACE diff --git a/bindgen-tests/tests/headers/issue-1291.hpp b/bindgen-tests/tests/headers/issue-1291.hpp index 4ec524f12f..313f7f7103 100644 --- a/bindgen-tests/tests/headers/issue-1291.hpp +++ b/bindgen-tests/tests/headers/issue-1291.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.25 +// bindgen-flags: \-\-rust-target=1.33 // bindgen-unstable struct __attribute__((aligned(16))) RTCRay diff --git a/bindgen-tests/tests/headers/issue-2966.h b/bindgen-tests/tests/headers/issue-2966.h new file mode 100644 index 0000000000..3f00dec65d --- /dev/null +++ b/bindgen-tests/tests/headers/issue-2966.h @@ -0,0 +1,6 @@ +// bindgen-flags: --default-alias-style=new_type +// bindgen-parse-callbacks: type-visibility + +typedef const char * pub_var1; +typedef const char * pubcrate_var2; +typedef const char * private_var3; diff --git a/bindgen-tests/tests/headers/issue-3027.hpp b/bindgen-tests/tests/headers/issue-3027.hpp new file mode 100644 index 0000000000..d9b87ee6e2 --- /dev/null +++ b/bindgen-tests/tests/headers/issue-3027.hpp @@ -0,0 +1,6 @@ +// bindgen-flags: --enable-cxx-namespaces + +namespace regression { + template class A { char c[N]; }; + class C { A<3> a; }; +} diff --git a/bindgen-tests/tests/headers/issue-493_1_0.hpp b/bindgen-tests/tests/headers/issue-493_1_0.hpp deleted file mode 100644 index af6fd47c41..0000000000 --- a/bindgen-tests/tests/headers/issue-493_1_0.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq --rustified-enum ".*" - -template -class basic_string -{ -public: - typedef unsigned long long size_type; - typedef char value_type; - typedef value_type * pointer; - - struct __long - { - size_type __cap_; - size_type __size_; - pointer __data_; - }; - - enum {__min_cap = (sizeof(__long) - 1)/sizeof(value_type) > 2 ? - (sizeof(__long) - 1)/sizeof(value_type) : 2}; - - struct __short - { - union - { - unsigned char __size_; - value_type __lx; - }; - value_type __data_[__min_cap]; - }; - - union __ulx{__long __lx; __short __lxx;}; - - enum {__n_words = sizeof(__ulx) / sizeof(size_type)}; - - struct __raw - { - size_type __words[__n_words]; - }; - - struct __rep - { - union - { - __long __l; - __short __s; - __raw __r; - }; - }; -}; diff --git a/bindgen-tests/tests/headers/issue-537-repr-packed-n.h b/bindgen-tests/tests/headers/issue-537-repr-packed-n.h index f4c0070a4a..7beaf88383 100644 --- a/bindgen-tests/tests/headers/issue-537-repr-packed-n.h +++ b/bindgen-tests/tests/headers/issue-537-repr-packed-n.h @@ -6,7 +6,7 @@ struct AlignedToOne { int i; } __attribute__ ((packed,aligned(1))); -/// This should be be packed because Rust 1.33 has `#[repr(packed(N))]`. +/// This should be packed because Rust 1.33 has `#[repr(packed(N))]`. struct AlignedToTwo { int i; } __attribute__ ((packed,aligned(2))); @@ -25,7 +25,7 @@ struct PackedToOne { #pragma pack(2) -/// This should be be packed because Rust 1.33 has `#[repr(packed(N))]`. +/// This should be packed because Rust 1.33 has `#[repr(packed(N))]`. struct PackedToTwo { int x; int y; diff --git a/bindgen-tests/tests/headers/issue-753.h b/bindgen-tests/tests/headers/issue-753.h new file mode 100644 index 0000000000..3a6c82528a --- /dev/null +++ b/bindgen-tests/tests/headers/issue-753.h @@ -0,0 +1,12 @@ +// bindgen-flags: --clang-macro-fallback + +#ifndef ISSUE_753_H +#define ISSUE_753_H + +#define UINT32_C(c) c ## U + +#define CONST UINT32_C(5) +#define OTHER_CONST UINT32_C(6) +#define LARGE_CONST UINT32_C(6 << 8) + +#endif diff --git a/bindgen-tests/tests/headers/jsval_layout_opaque_1_0.hpp b/bindgen-tests/tests/headers/jsval_layout_opaque_1_0.hpp deleted file mode 100644 index c8e665516b..0000000000 --- a/bindgen-tests/tests/headers/jsval_layout_opaque_1_0.hpp +++ /dev/null @@ -1,425 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq --rustified-enum ".*" -// bindgen-flags: -- -std=c++11 - -/** - * These typedefs are hacky, but keep our tests consistent across 64-bit - * platforms, otherwise the id's change and our CI is unhappy. - */ -typedef unsigned char uint8_t; -typedef int int32_t; -typedef unsigned int uint32_t; -typedef unsigned long long uint64_t; -typedef unsigned long long size_t; -typedef unsigned long long uintptr_t; - - -#define JS_PUNBOX64 -#define IS_LITTLE_ENDIAN - -/* - * Try to get jsvals 64-bit aligned. We could almost assert that all values are - * aligned, but MSVC and GCC occasionally break alignment. - */ -#if defined(__GNUC__) || defined(__xlc__) || defined(__xlC__) -# define JSVAL_ALIGNMENT __attribute__((aligned (8))) -#elif defined(_MSC_VER) - /* - * Structs can be aligned with MSVC, but not if they are used as parameters, - * so we just don't try to align. - */ -# define JSVAL_ALIGNMENT -#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) -# define JSVAL_ALIGNMENT -#elif defined(__HP_cc) || defined(__HP_aCC) -# define JSVAL_ALIGNMENT -#endif - -#if defined(JS_PUNBOX64) -# define JSVAL_TAG_SHIFT 47 -#endif - -/* - * We try to use enums so that printing a jsval_layout in the debugger shows - * nice symbolic type tags, however we can only do this when we can force the - * underlying type of the enum to be the desired size. - */ -#if !defined(__SUNPRO_CC) && !defined(__xlC__) - -#if defined(_MSC_VER) -# define JS_ENUM_HEADER(id, type) enum id : type -# define JS_ENUM_FOOTER(id) -#else -# define JS_ENUM_HEADER(id, type) enum id -# define JS_ENUM_FOOTER(id) __attribute__((packed)) -#endif - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueType, uint8_t) -{ - JSVAL_TYPE_DOUBLE = 0x00, - JSVAL_TYPE_INT32 = 0x01, - JSVAL_TYPE_UNDEFINED = 0x02, - JSVAL_TYPE_BOOLEAN = 0x03, - JSVAL_TYPE_MAGIC = 0x04, - JSVAL_TYPE_STRING = 0x05, - JSVAL_TYPE_SYMBOL = 0x06, - JSVAL_TYPE_NULL = 0x07, - JSVAL_TYPE_OBJECT = 0x08, - - /* These never appear in a jsval; they are only provided as an out-of-band value. */ - JSVAL_TYPE_UNKNOWN = 0x20, - JSVAL_TYPE_MISSING = 0x21 -} JS_ENUM_FOOTER(JSValueType); - -static_assert(sizeof(JSValueType) == 1, - "compiler typed enum support is apparently buggy"); - -#if defined(JS_NUNBOX32) - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueTag, uint32_t) -{ - JSVAL_TAG_CLEAR = 0xFFFFFF80, - JSVAL_TAG_INT32 = JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32, - JSVAL_TAG_UNDEFINED = JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED, - JSVAL_TAG_STRING = JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING, - JSVAL_TAG_SYMBOL = JSVAL_TAG_CLEAR | JSVAL_TYPE_SYMBOL, - JSVAL_TAG_BOOLEAN = JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN, - JSVAL_TAG_MAGIC = JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC, - JSVAL_TAG_NULL = JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL, - JSVAL_TAG_OBJECT = JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT -} JS_ENUM_FOOTER(JSValueTag); - -static_assert(sizeof(JSValueTag) == sizeof(uint32_t), - "compiler typed enum support is apparently buggy"); - -#elif defined(JS_PUNBOX64) - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueTag, uint32_t) -{ - JSVAL_TAG_MAX_DOUBLE = 0x1FFF0, - JSVAL_TAG_INT32 = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_INT32, - JSVAL_TAG_UNDEFINED = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_UNDEFINED, - JSVAL_TAG_STRING = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_STRING, - JSVAL_TAG_SYMBOL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_SYMBOL, - JSVAL_TAG_BOOLEAN = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_BOOLEAN, - JSVAL_TAG_MAGIC = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_MAGIC, - JSVAL_TAG_NULL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_NULL, - JSVAL_TAG_OBJECT = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_OBJECT -} JS_ENUM_FOOTER(JSValueTag); - -static_assert(sizeof(JSValueTag) == sizeof(uint32_t), - "compiler typed enum support is apparently buggy"); - -JS_ENUM_HEADER(JSValueShiftedTag, uint64_t) -{ - JSVAL_SHIFTED_TAG_MAX_DOUBLE = ((((uint64_t)JSVAL_TAG_MAX_DOUBLE) << JSVAL_TAG_SHIFT) | 0xFFFFFFFF), - JSVAL_SHIFTED_TAG_INT32 = (((uint64_t)JSVAL_TAG_INT32) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_UNDEFINED = (((uint64_t)JSVAL_TAG_UNDEFINED) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_STRING = (((uint64_t)JSVAL_TAG_STRING) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_SYMBOL = (((uint64_t)JSVAL_TAG_SYMBOL) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_BOOLEAN = (((uint64_t)JSVAL_TAG_BOOLEAN) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_MAGIC = (((uint64_t)JSVAL_TAG_MAGIC) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_NULL = (((uint64_t)JSVAL_TAG_NULL) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_OBJECT = (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT) -} JS_ENUM_FOOTER(JSValueShiftedTag); - -static_assert(sizeof(JSValueShiftedTag) == sizeof(uint64_t), - "compiler typed enum support is apparently buggy"); - -#endif - -/* - * All our supported compilers implement C++11 |enum Foo : T| syntax, so don't - * expose these macros. (This macro exists *only* because gcc bug 51242 - * makes bit-fields of - * typed enums trigger a warning that can't be turned off. Don't expose it - * beyond this file!) - */ -#undef JS_ENUM_HEADER -#undef JS_ENUM_FOOTER - -#else /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ - -typedef uint8_t JSValueType; -#define JSVAL_TYPE_DOUBLE ((uint8_t)0x00) -#define JSVAL_TYPE_INT32 ((uint8_t)0x01) -#define JSVAL_TYPE_UNDEFINED ((uint8_t)0x02) -#define JSVAL_TYPE_BOOLEAN ((uint8_t)0x03) -#define JSVAL_TYPE_MAGIC ((uint8_t)0x04) -#define JSVAL_TYPE_STRING ((uint8_t)0x05) -#define JSVAL_TYPE_SYMBOL ((uint8_t)0x06) -#define JSVAL_TYPE_NULL ((uint8_t)0x07) -#define JSVAL_TYPE_OBJECT ((uint8_t)0x08) -#define JSVAL_TYPE_UNKNOWN ((uint8_t)0x20) - -#if defined(JS_NUNBOX32) - -typedef uint32_t JSValueTag; -#define JSVAL_TAG_CLEAR ((uint32_t)(0xFFFFFF80)) -#define JSVAL_TAG_INT32 ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32)) -#define JSVAL_TAG_UNDEFINED ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED)) -#define JSVAL_TAG_STRING ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING)) -#define JSVAL_TAG_SYMBOL ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_SYMBOL)) -#define JSVAL_TAG_BOOLEAN ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN)) -#define JSVAL_TAG_MAGIC ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC)) -#define JSVAL_TAG_NULL ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL)) -#define JSVAL_TAG_OBJECT ((uint32_t)(JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT)) - -#elif defined(JS_PUNBOX64) - -typedef uint32_t JSValueTag; -#define JSVAL_TAG_MAX_DOUBLE ((uint32_t)(0x1FFF0)) -#define JSVAL_TAG_INT32 (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_INT32) -#define JSVAL_TAG_UNDEFINED (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_UNDEFINED) -#define JSVAL_TAG_STRING (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_STRING) -#define JSVAL_TAG_SYMBOL (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_SYMBOL) -#define JSVAL_TAG_BOOLEAN (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_BOOLEAN) -#define JSVAL_TAG_MAGIC (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_MAGIC) -#define JSVAL_TAG_NULL (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_NULL) -#define JSVAL_TAG_OBJECT (uint32_t)(JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_OBJECT) - -typedef uint64_t JSValueShiftedTag; -#define JSVAL_SHIFTED_TAG_MAX_DOUBLE ((((uint64_t)JSVAL_TAG_MAX_DOUBLE) << JSVAL_TAG_SHIFT) | 0xFFFFFFFF) -#define JSVAL_SHIFTED_TAG_INT32 (((uint64_t)JSVAL_TAG_INT32) << JSVAL_TAG_SHIFT) -#define JSVAL_SHIFTED_TAG_UNDEFINED (((uint64_t)JSVAL_TAG_UNDEFINED) << JSVAL_TAG_SHIFT) -#define JSVAL_SHIFTED_TAG_STRING (((uint64_t)JSVAL_TAG_STRING) << JSVAL_TAG_SHIFT) -#define JSVAL_SHIFTED_TAG_SYMBOL (((uint64_t)JSVAL_TAG_SYMBOL) << JSVAL_TAG_SHIFT) -#define JSVAL_SHIFTED_TAG_BOOLEAN (((uint64_t)JSVAL_TAG_BOOLEAN) << JSVAL_TAG_SHIFT) -#define JSVAL_SHIFTED_TAG_MAGIC (((uint64_t)JSVAL_TAG_MAGIC) << JSVAL_TAG_SHIFT) -#define JSVAL_SHIFTED_TAG_NULL (((uint64_t)JSVAL_TAG_NULL) << JSVAL_TAG_SHIFT) -#define JSVAL_SHIFTED_TAG_OBJECT (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT) - -#endif /* JS_PUNBOX64 */ -#endif /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ - -#if defined(JS_NUNBOX32) - -#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_CLEAR | (type))) - -#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL -#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT -#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 -#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING - -#elif defined(JS_PUNBOX64) - -#define JSVAL_PAYLOAD_MASK 0x00007FFFFFFFFFFFLL -#define JSVAL_TAG_MASK 0xFFFF800000000000LL -#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_MAX_DOUBLE | (type))) -#define JSVAL_TYPE_TO_SHIFTED_TAG(type) (((uint64_t)JSVAL_TYPE_TO_TAG(type)) << JSVAL_TAG_SHIFT) - -#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL -#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT -#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 -#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING - -#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_OBJ_OR_NULL_SET JSVAL_SHIFTED_TAG_NULL -#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET JSVAL_SHIFTED_TAG_OBJECT -#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET JSVAL_SHIFTED_TAG_UNDEFINED -#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET JSVAL_SHIFTED_TAG_STRING - -#endif /* JS_PUNBOX64 */ - -typedef enum JSWhyMagic -{ - /** a hole in a native object's elements */ - JS_ELEMENTS_HOLE, - - /** there is not a pending iterator value */ - JS_NO_ITER_VALUE, - - /** exception value thrown when closing a generator */ - JS_GENERATOR_CLOSING, - - /** compiler sentinel value */ - JS_NO_CONSTANT, - - /** used in debug builds to catch tracing errors */ - JS_THIS_POISON, - - /** used in debug builds to catch tracing errors */ - JS_ARG_POISON, - - /** an empty subnode in the AST serializer */ - JS_SERIALIZE_NO_NODE, - - /** lazy arguments value on the stack */ - JS_LAZY_ARGUMENTS, - - /** optimized-away 'arguments' value */ - JS_OPTIMIZED_ARGUMENTS, - - /** magic value passed to natives to indicate construction */ - JS_IS_CONSTRUCTING, - - /** arguments.callee has been overwritten */ - JS_OVERWRITTEN_CALLEE, - - /** value of static block object slot */ - JS_BLOCK_NEEDS_CLONE, - - /** see class js::HashableValue */ - JS_HASH_KEY_EMPTY, - - /** error while running Ion code */ - JS_ION_ERROR, - - /** missing recover instruction result */ - JS_ION_BAILOUT, - - /** optimized out slot */ - JS_OPTIMIZED_OUT, - - /** uninitialized lexical bindings that produce ReferenceError on touch. */ - JS_UNINITIALIZED_LEXICAL, - - /** for local use */ - JS_GENERIC_MAGIC, - - JS_WHY_MAGIC_COUNT -} JSWhyMagic; - -#if defined(IS_LITTLE_ENDIAN) -# if defined(JS_NUNBOX32) -typedef union jsval_layout -{ - uint64_t asBits; - struct { - union { - int32_t i32; - uint32_t u32; - uint32_t boo; // Don't use |bool| -- it must be four bytes. - JSString* str; - JS::Symbol* sym; - JSObject* obj; - js::gc::Cell* cell; - void* ptr; - JSWhyMagic why; - size_t word; - uintptr_t uintptr; - } payload; - JSValueTag tag; - } s; - double asDouble; - void* asPtr; -} JSVAL_ALIGNMENT jsval_layout; -# elif defined(JS_PUNBOX64) -typedef union jsval_layout -{ - uint64_t asBits; -#if !defined(_WIN64) - /* MSVC does not pack these correctly :-( */ - struct { - uint64_t payload47 : 47; - JSValueTag tag : 17; - } debugView; -#endif - struct { - union { - int32_t i32; - uint32_t u32; - JSWhyMagic why; - } payload; - } s; - double asDouble; - void* asPtr; - size_t asWord; - uintptr_t asUIntPtr; -} JSVAL_ALIGNMENT jsval_layout; -# endif /* JS_PUNBOX64 */ -#else /* defined(IS_LITTLE_ENDIAN) */ -# if defined(JS_NUNBOX32) -typedef union jsval_layout -{ - uint64_t asBits; - struct { - JSValueTag tag; - union { - int32_t i32; - uint32_t u32; - uint32_t boo; // Don't use |bool| -- it must be four bytes. - JSString* str; - JS::Symbol* sym; - JSObject* obj; - js::gc::Cell* cell; - void* ptr; - JSWhyMagic why; - size_t word; - uintptr_t uintptr; - } payload; - } s; - double asDouble; - void* asPtr; -} JSVAL_ALIGNMENT jsval_layout; -# elif defined(JS_PUNBOX64) -typedef union jsval_layout -{ - uint64_t asBits; - struct { - JSValueTag tag : 17; - uint64_t payload47 : 47; - } debugView; - struct { - uint32_t padding; - union { - int32_t i32; - uint32_t u32; - JSWhyMagic why; - } payload; - } s; - double asDouble; - void* asPtr; - size_t asWord; - uintptr_t asUIntPtr; -} JSVAL_ALIGNMENT jsval_layout; -# endif /* JS_PUNBOX64 */ -#endif /* defined(IS_LITTLE_ENDIAN) */ - -/* - * For codesize purposes on some platforms, it's important that the - * compiler know that JS::Values constructed from constant values can be - * folded to constant bit patterns at compile time, rather than - * constructed at runtime. Doing this requires a fair amount of C++11 - * features, which are not supported on all of our compilers. Set up - * some defines and helper macros in an attempt to confine the ugliness - * here, rather than scattering it all about the file. The important - * features are: - * - * - constexpr; - * - defaulted functions; - * - C99-style designated initializers. - */ -#if defined(__clang__) -# if __has_feature(cxx_constexpr) && __has_feature(cxx_defaulted_functions) -# define JS_VALUE_IS_CONSTEXPR -# endif -#elif defined(__GNUC__) -/* - * We need 4.5 for defaulted functions, 4.6 for constexpr, 4.7 because 4.6 - * doesn't understand |(X) { .field = ... }| syntax, and 4.7.3 because - * versions prior to that have bugs in the C++ front-end that cause crashes. - */ -# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 3) -# define JS_VALUE_IS_CONSTEXPR -# endif -#endif - -#if defined(JS_VALUE_IS_CONSTEXPR) -# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ - return (jsval_layout) { .asBits = (BITS) } -# define JS_VALUE_CONSTEXPR MOZ_CONSTEXPR -# define JS_VALUE_CONSTEXPR_VAR MOZ_CONSTEXPR_VAR -#else -# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ - jsval_layout l; \ - l.asBits = (BITS); \ - return l; -# define JS_VALUE_CONSTEXPR -# define JS_VALUE_CONSTEXPR_VAR const -#endif - -struct Value { - jsval_layout data; -}; diff --git a/bindgen-tests/tests/headers/keywords.h b/bindgen-tests/tests/headers/keywords.h index 3b3fc4976e..49924193c7 100644 --- a/bindgen-tests/tests/headers/keywords.h +++ b/bindgen-tests/tests/headers/keywords.h @@ -21,6 +21,7 @@ int box; int crate; int false; int fn; +int gen; int impl; int in; int let; diff --git a/bindgen-tests/tests/headers/layout.h b/bindgen-tests/tests/headers/layout.h index b290ee856b..0b3df26347 100644 --- a/bindgen-tests/tests/headers/layout.h +++ b/bindgen-tests/tests/headers/layout.h @@ -1,10 +1,13 @@ -// bindgen-flags: --rust-target 1.21 +// bindgen-flags: \-\-rust-target=1.33 // // FIXME: https://github.com/rust-lang/rust-bindgen/issues/1498 + +#if 0 struct header { char proto; unsigned int size __attribute__ ((packed)); unsigned char data[] __attribute__ ((aligned(8))); } __attribute__ ((aligned, packed)); +#endif diff --git a/bindgen-tests/tests/headers/layout_eth_conf_1_0.h b/bindgen-tests/tests/headers/layout_eth_conf_1_0.h deleted file mode 100644 index 7da582ba19..0000000000 --- a/bindgen-tests/tests/headers/layout_eth_conf_1_0.h +++ /dev/null @@ -1,429 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq --rustified-enum ".*" - -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; -typedef unsigned long long uint64_t; - -/** - * Simple flags are used for rte_eth_conf.rxmode.mq_mode. - */ -#define ETH_MQ_RX_RSS_FLAG 0x1 -#define ETH_MQ_RX_DCB_FLAG 0x2 -#define ETH_MQ_RX_VMDQ_FLAG 0x4 - -/* Definitions used for VMDQ and DCB functionality */ -#define ETH_VMDQ_MAX_VLAN_FILTERS 64 /**< Maximum nb. of VMDQ vlan filters. */ -#define ETH_DCB_NUM_USER_PRIORITIES 8 /**< Maximum nb. of DCB priorities. */ -#define ETH_VMDQ_DCB_NUM_QUEUES 128 /**< Maximum nb. of VMDQ DCB queues. */ -#define ETH_DCB_NUM_QUEUES 128 /**< Maximum nb. of DCB queues. */ - -/** - * A set of values to identify what method is to be used to route - * packets to multiple queues. - */ -enum rte_eth_rx_mq_mode { - /** None of DCB,RSS or VMDQ mode */ - ETH_MQ_RX_NONE = 0, - - /** For RX side, only RSS is on */ - ETH_MQ_RX_RSS = ETH_MQ_RX_RSS_FLAG, - /** For RX side,only DCB is on. */ - ETH_MQ_RX_DCB = ETH_MQ_RX_DCB_FLAG, - /** Both DCB and RSS enable */ - ETH_MQ_RX_DCB_RSS = ETH_MQ_RX_RSS_FLAG | ETH_MQ_RX_DCB_FLAG, - - /** Only VMDQ, no RSS nor DCB */ - ETH_MQ_RX_VMDQ_ONLY = ETH_MQ_RX_VMDQ_FLAG, - /** RSS mode with VMDQ */ - ETH_MQ_RX_VMDQ_RSS = ETH_MQ_RX_RSS_FLAG | ETH_MQ_RX_VMDQ_FLAG, - /** Use VMDQ+DCB to route traffic to queues */ - ETH_MQ_RX_VMDQ_DCB = ETH_MQ_RX_VMDQ_FLAG | ETH_MQ_RX_DCB_FLAG, - /** Enable both VMDQ and DCB in VMDq */ - ETH_MQ_RX_VMDQ_DCB_RSS = ETH_MQ_RX_RSS_FLAG | ETH_MQ_RX_DCB_FLAG | - ETH_MQ_RX_VMDQ_FLAG, -}; - -/** - * A structure used to configure the RX features of an Ethernet port. - */ -struct rte_eth_rxmode { - /** The multi-queue packet distribution mode to be used, e.g. RSS. */ - enum rte_eth_rx_mq_mode mq_mode; - uint32_t max_rx_pkt_len; /**< Only used if jumbo_frame enabled. */ - uint16_t split_hdr_size; /**< hdr buf size (header_split enabled).*/ - __extension__ - uint16_t header_split : 1, /**< Header Split enable. */ - hw_ip_checksum : 1, /**< IP/UDP/TCP checksum offload enable. */ - hw_vlan_filter : 1, /**< VLAN filter enable. */ - hw_vlan_strip : 1, /**< VLAN strip enable. */ - hw_vlan_extend : 1, /**< Extended VLAN enable. */ - jumbo_frame : 1, /**< Jumbo Frame Receipt enable. */ - hw_strip_crc : 1, /**< Enable CRC stripping by hardware. */ - enable_scatter : 1, /**< Enable scatter packets rx handler */ - enable_lro : 1; /**< Enable LRO */ -}; - -/** - * A set of values to identify what method is to be used to transmit - * packets using multi-TCs. - */ -enum rte_eth_tx_mq_mode { - ETH_MQ_TX_NONE = 0, /**< It is in neither DCB nor VT mode. */ - ETH_MQ_TX_DCB, /**< For TX side,only DCB is on. */ - ETH_MQ_TX_VMDQ_DCB, /**< For TX side,both DCB and VT is on. */ - ETH_MQ_TX_VMDQ_ONLY, /**< Only VT on, no DCB */ -}; - -/** - * A structure used to configure the TX features of an Ethernet port. - */ -struct rte_eth_txmode { - enum rte_eth_tx_mq_mode mq_mode; /**< TX multi-queues mode. */ - - /* For i40e specifically */ - uint16_t pvid; - __extension__ - uint8_t hw_vlan_reject_tagged : 1, - /**< If set, reject sending out tagged pkts */ - hw_vlan_reject_untagged : 1, - /**< If set, reject sending out untagged pkts */ - hw_vlan_insert_pvid : 1; - /**< If set, enable port based VLAN insertion */ -}; - -/** - * A structure used to configure the Receive Side Scaling (RSS) feature - * of an Ethernet port. - * If not NULL, the *rss_key* pointer of the *rss_conf* structure points - * to an array holding the RSS key to use for hashing specific header - * fields of received packets. The length of this array should be indicated - * by *rss_key_len* below. Otherwise, a default random hash key is used by - * the device driver. - * - * The *rss_key_len* field of the *rss_conf* structure indicates the length - * in bytes of the array pointed by *rss_key*. To be compatible, this length - * will be checked in i40e only. Others assume 40 bytes to be used as before. - * - * The *rss_hf* field of the *rss_conf* structure indicates the different - * types of IPv4/IPv6 packets to which the RSS hashing must be applied. - * Supplying an *rss_hf* equal to zero disables the RSS feature. - */ -struct rte_eth_rss_conf { - uint8_t *rss_key; /**< If not NULL, 40-byte hash key. */ - uint8_t rss_key_len; /**< hash key length in bytes. */ - uint64_t rss_hf; /**< Hash functions to apply - see below. */ -}; - -/** - * This enum indicates the possible number of traffic classes - * in DCB configratioins - */ -enum rte_eth_nb_tcs { - ETH_4_TCS = 4, /**< 4 TCs with DCB. */ - ETH_8_TCS = 8 /**< 8 TCs with DCB. */ -}; - -/** - * This enum indicates the possible number of queue pools - * in VMDQ configurations. - */ -enum rte_eth_nb_pools { - ETH_8_POOLS = 8, /**< 8 VMDq pools. */ - ETH_16_POOLS = 16, /**< 16 VMDq pools. */ - ETH_32_POOLS = 32, /**< 32 VMDq pools. */ - ETH_64_POOLS = 64 /**< 64 VMDq pools. */ -}; - -/** - * A structure used to configure the VMDQ+DCB feature - * of an Ethernet port. - * - * Using this feature, packets are routed to a pool of queues, based - * on the vlan ID in the vlan tag, and then to a specific queue within - * that pool, using the user priority vlan tag field. - * - * A default pool may be used, if desired, to route all traffic which - * does not match the vlan filter rules. - */ -struct rte_eth_vmdq_dcb_conf { - enum rte_eth_nb_pools nb_queue_pools; /**< With DCB, 16 or 32 pools */ - uint8_t enable_default_pool; /**< If non-zero, use a default pool */ - uint8_t default_pool; /**< The default pool, if applicable */ - uint8_t nb_pool_maps; /**< We can have up to 64 filters/mappings */ - struct { - uint16_t vlan_id; /**< The vlan ID of the received frame */ - uint64_t pools; /**< Bitmask of pools for packet rx */ - } pool_map[ETH_VMDQ_MAX_VLAN_FILTERS]; /**< VMDq vlan pool maps. */ - uint8_t dcb_tc[ETH_DCB_NUM_USER_PRIORITIES]; - /**< Selects a queue in a pool */ -}; - -/* This structure may be extended in future. */ -struct rte_eth_dcb_rx_conf { - enum rte_eth_nb_tcs nb_tcs; /**< Possible DCB TCs, 4 or 8 TCs */ - /** Traffic class each UP mapped to. */ - uint8_t dcb_tc[ETH_DCB_NUM_USER_PRIORITIES]; -}; - -struct rte_eth_vmdq_dcb_tx_conf { - enum rte_eth_nb_pools nb_queue_pools; /**< With DCB, 16 or 32 pools. */ - /** Traffic class each UP mapped to. */ - uint8_t dcb_tc[ETH_DCB_NUM_USER_PRIORITIES]; -}; - -struct rte_eth_dcb_tx_conf { - enum rte_eth_nb_tcs nb_tcs; /**< Possible DCB TCs, 4 or 8 TCs. */ - /** Traffic class each UP mapped to. */ - uint8_t dcb_tc[ETH_DCB_NUM_USER_PRIORITIES]; -}; - -struct rte_eth_vmdq_tx_conf { - enum rte_eth_nb_pools nb_queue_pools; /**< VMDq mode, 64 pools. */ -}; - -struct rte_eth_vmdq_rx_conf { - enum rte_eth_nb_pools nb_queue_pools; /**< VMDq only mode, 8 or 64 pools */ - uint8_t enable_default_pool; /**< If non-zero, use a default pool */ - uint8_t default_pool; /**< The default pool, if applicable */ - uint8_t enable_loop_back; /**< Enable VT loop back */ - uint8_t nb_pool_maps; /**< We can have up to 64 filters/mappings */ - uint32_t rx_mode; /**< Flags from ETH_VMDQ_ACCEPT_* */ - struct { - uint16_t vlan_id; /**< The vlan ID of the received frame */ - uint64_t pools; /**< Bitmask of pools for packet rx */ - } pool_map[ETH_VMDQ_MAX_VLAN_FILTERS]; /**< VMDq vlan pool maps. */ -}; - -/** - * Flow Director setting modes: none, signature or perfect. - */ -enum rte_fdir_mode { - RTE_FDIR_MODE_NONE = 0, /**< Disable FDIR support. */ - RTE_FDIR_MODE_SIGNATURE, /**< Enable FDIR signature filter mode. */ - RTE_FDIR_MODE_PERFECT, /**< Enable FDIR perfect filter mode. */ - RTE_FDIR_MODE_PERFECT_MAC_VLAN, /**< Enable FDIR filter mode - MAC VLAN. */ - RTE_FDIR_MODE_PERFECT_TUNNEL, /**< Enable FDIR filter mode - tunnel. */ -}; - -/** - * Memory space that can be configured to store Flow Director filters - * in the board memory. - */ -enum rte_fdir_pballoc_type { - RTE_FDIR_PBALLOC_64K = 0, /**< 64k. */ - RTE_FDIR_PBALLOC_128K, /**< 128k. */ - RTE_FDIR_PBALLOC_256K, /**< 256k. */ -}; - -/** - * Select report mode of FDIR hash information in RX descriptors. - */ -enum rte_fdir_status_mode { - RTE_FDIR_NO_REPORT_STATUS = 0, /**< Never report FDIR hash. */ - RTE_FDIR_REPORT_STATUS, /**< Only report FDIR hash for matching pkts. */ - RTE_FDIR_REPORT_STATUS_ALWAYS, /**< Always report FDIR hash. */ -}; - -/** - * A structure used to define the input for IPV4 flow - */ -struct rte_eth_ipv4_flow { - uint32_t src_ip; /**< IPv4 source address in big endian. */ - uint32_t dst_ip; /**< IPv4 destination address in big endian. */ - uint8_t tos; /**< Type of service to match. */ - uint8_t ttl; /**< Time to live to match. */ - uint8_t proto; /**< Protocol, next header in big endian. */ -}; - -/** - * A structure used to define the input for IPV6 flow - */ -struct rte_eth_ipv6_flow { - uint32_t src_ip[4]; /**< IPv6 source address in big endian. */ - uint32_t dst_ip[4]; /**< IPv6 destination address in big endian. */ - uint8_t tc; /**< Traffic class to match. */ - uint8_t proto; /**< Protocol, next header to match. */ - uint8_t hop_limits; /**< Hop limits to match. */ -}; - -/** - * A structure used to configure FDIR masks that are used by the device - * to match the various fields of RX packet headers. - */ -struct rte_eth_fdir_masks { - uint16_t vlan_tci_mask; /**< Bit mask for vlan_tci in big endian */ - /** Bit mask for ipv4 flow in big endian. */ - struct rte_eth_ipv4_flow ipv4_mask; - /** Bit maks for ipv6 flow in big endian. */ - struct rte_eth_ipv6_flow ipv6_mask; - /** Bit mask for L4 source port in big endian. */ - uint16_t src_port_mask; - /** Bit mask for L4 destination port in big endian. */ - uint16_t dst_port_mask; - /** 6 bit mask for proper 6 bytes of Mac address, bit 0 matches the - first byte on the wire */ - uint8_t mac_addr_byte_mask; - /** Bit mask for tunnel ID in big endian. */ - uint32_t tunnel_id_mask; - uint8_t tunnel_type_mask; /**< 1 - Match tunnel type, - 0 - Ignore tunnel type. */ -}; - -/** - * Payload type - */ -enum rte_eth_payload_type { - RTE_ETH_PAYLOAD_UNKNOWN = 0, - RTE_ETH_RAW_PAYLOAD, - RTE_ETH_L2_PAYLOAD, - RTE_ETH_L3_PAYLOAD, - RTE_ETH_L4_PAYLOAD, - RTE_ETH_PAYLOAD_MAX = 8, -}; - -#define RTE_ETH_FDIR_MAX_FLEXLEN 16 /**< Max length of flexbytes. */ -#define RTE_ETH_INSET_SIZE_MAX 128 /**< Max length of input set. */ - -/** - * A structure used to select bytes extracted from the protocol layers to - * flexible payload for filter - */ -struct rte_eth_flex_payload_cfg { - enum rte_eth_payload_type type; /**< Payload type */ - uint16_t src_offset[RTE_ETH_FDIR_MAX_FLEXLEN]; - /**< Offset in bytes from the beginning of packet's payload - src_offset[i] indicates the flexbyte i's offset in original - packet payload. This value should be less than - flex_payload_limit in struct rte_eth_fdir_info.*/ -}; - -/** - * A structure used to define FDIR masks for flexible payload - * for each flow type - */ -struct rte_eth_fdir_flex_mask { - uint16_t flow_type; - uint8_t mask[RTE_ETH_FDIR_MAX_FLEXLEN]; - /**< Mask for the whole flexible payload */ -}; - - -/* - * A packet can be identified by hardware as different flow types. Different - * NIC hardwares may support different flow types. - * Basically, the NIC hardware identifies the flow type as deep protocol as - * possible, and exclusively. For example, if a packet is identified as - * 'RTE_ETH_FLOW_NONFRAG_IPV4_TCP', it will not be any of other flow types, - * though it is an actual IPV4 packet. - * Note that the flow types are used to define RSS offload types in - * rte_ethdev.h. - */ -#define RTE_ETH_FLOW_UNKNOWN 0 -#define RTE_ETH_FLOW_RAW 1 -#define RTE_ETH_FLOW_IPV4 2 -#define RTE_ETH_FLOW_FRAG_IPV4 3 -#define RTE_ETH_FLOW_NONFRAG_IPV4_TCP 4 -#define RTE_ETH_FLOW_NONFRAG_IPV4_UDP 5 -#define RTE_ETH_FLOW_NONFRAG_IPV4_SCTP 6 -#define RTE_ETH_FLOW_NONFRAG_IPV4_OTHER 7 -#define RTE_ETH_FLOW_IPV6 8 -#define RTE_ETH_FLOW_FRAG_IPV6 9 -#define RTE_ETH_FLOW_NONFRAG_IPV6_TCP 10 -#define RTE_ETH_FLOW_NONFRAG_IPV6_UDP 11 -#define RTE_ETH_FLOW_NONFRAG_IPV6_SCTP 12 -#define RTE_ETH_FLOW_NONFRAG_IPV6_OTHER 13 -#define RTE_ETH_FLOW_L2_PAYLOAD 14 -#define RTE_ETH_FLOW_IPV6_EX 15 -#define RTE_ETH_FLOW_IPV6_TCP_EX 16 -#define RTE_ETH_FLOW_IPV6_UDP_EX 17 -#define RTE_ETH_FLOW_PORT 18 - /**< Consider device port number as a flow differentiator */ -#define RTE_ETH_FLOW_VXLAN 19 /**< VXLAN protocol based flow */ -#define RTE_ETH_FLOW_GENEVE 20 /**< GENEVE protocol based flow */ -#define RTE_ETH_FLOW_NVGRE 21 /**< NVGRE protocol based flow */ -#define RTE_ETH_FLOW_MAX 22 - -/** - * A structure used to define all flexible payload related setting - * include flex payload and flex mask - */ -struct rte_eth_fdir_flex_conf { - uint16_t nb_payloads; /**< The number of following payload cfg */ - uint16_t nb_flexmasks; /**< The number of following mask */ - struct rte_eth_flex_payload_cfg flex_set[RTE_ETH_PAYLOAD_MAX]; - /**< Flex payload configuration for each payload type */ - struct rte_eth_fdir_flex_mask flex_mask[RTE_ETH_FLOW_MAX]; - /**< Flex mask configuration for each flow type */ -}; - -/** - * A structure used to configure the Flow Director (FDIR) feature - * of an Ethernet port. - * - * If mode is RTE_FDIR_DISABLE, the pballoc value is ignored. - */ -struct rte_fdir_conf { - enum rte_fdir_mode mode; /**< Flow Director mode. */ - enum rte_fdir_pballoc_type pballoc; /**< Space for FDIR filters. */ - enum rte_fdir_status_mode status; /**< How to report FDIR hash. */ - /** RX queue of packets matching a "drop" filter in perfect mode. */ - uint8_t drop_queue; - struct rte_eth_fdir_masks mask; - struct rte_eth_fdir_flex_conf flex_conf; - /**< Flex payload configuration. */ -}; - -/** - * A structure used to enable/disable specific device interrupts. - */ -struct rte_intr_conf { - /** enable/disable lsc interrupt. 0 (default) - disable, 1 enable */ - uint16_t lsc; - /** enable/disable rxq interrupt. 0 (default) - disable, 1 enable */ - uint16_t rxq; -}; - -/** - * A structure used to configure an Ethernet port. - * Depending upon the RX multi-queue mode, extra advanced - * configuration settings may be needed. - */ -struct rte_eth_conf { - uint32_t link_speeds; /**< bitmap of ETH_LINK_SPEED_XXX of speeds to be - used. ETH_LINK_SPEED_FIXED disables link - autonegotiation, and a unique speed shall be - set. Otherwise, the bitmap defines the set of - speeds to be advertised. If the special value - ETH_LINK_SPEED_AUTONEG (0) is used, all speeds - supported are advertised. */ - struct rte_eth_rxmode rxmode; /**< Port RX configuration. */ - struct rte_eth_txmode txmode; /**< Port TX configuration. */ - uint32_t lpbk_mode; /**< Loopback operation mode. By default the value - is 0, meaning the loopback mode is disabled. - Read the datasheet of given ethernet controller - for details. The possible values of this field - are defined in implementation of each driver. */ - struct { - struct rte_eth_rss_conf rss_conf; /**< Port RSS configuration */ - struct rte_eth_vmdq_dcb_conf vmdq_dcb_conf; - /**< Port vmdq+dcb configuration. */ - struct rte_eth_dcb_rx_conf dcb_rx_conf; - /**< Port dcb RX configuration. */ - struct rte_eth_vmdq_rx_conf vmdq_rx_conf; - /**< Port vmdq RX configuration. */ - } rx_adv_conf; /**< Port RX filtering configuration (union). */ - union { - struct rte_eth_vmdq_dcb_tx_conf vmdq_dcb_tx_conf; - /**< Port vmdq+dcb TX configuration. */ - struct rte_eth_dcb_tx_conf dcb_tx_conf; - /**< Port dcb TX configuration. */ - struct rte_eth_vmdq_tx_conf vmdq_tx_conf; - /**< Port vmdq TX configuration. */ - } tx_adv_conf; /**< Port TX DCB configuration (union). */ - /** Currently,Priority Flow Control(PFC) are supported,if DCB with PFC - is needed,and the variable must be set ETH_DCB_PFC_SUPPORT. */ - uint32_t dcb_capability_en; - struct rte_fdir_conf fdir_conf; /**< FDIR configuration. */ - struct rte_intr_conf intr_conf; /**< Interrupt mode configuration. */ -}; diff --git a/bindgen-tests/tests/headers/layout_mbuf_1_0.h b/bindgen-tests/tests/headers/layout_mbuf_1_0.h deleted file mode 100644 index 2854de5038..0000000000 --- a/bindgen-tests/tests/headers/layout_mbuf_1_0.h +++ /dev/null @@ -1,189 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - - -#define RTE_CACHE_LINE_MIN_SIZE 64 /**< Minimum Cache line size. */ - -#define RTE_CACHE_LINE_SIZE 64 - -typedef char int8_t; -typedef short int16_t; -typedef int int32_t; -typedef long long int64_t; - -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; -typedef unsigned long long uint64_t; - -typedef uint64_t phys_addr_t; - -/** - * Force alignment - */ -#define __rte_aligned(a) __attribute__((__aligned__(a))) - -/** - * Force alignment to cache line. - */ -#define __rte_cache_aligned __rte_aligned(RTE_CACHE_LINE_SIZE) - -/** - * Force minimum cache line alignment. - */ -#define __rte_cache_min_aligned __rte_aligned(RTE_CACHE_LINE_MIN_SIZE) - -/* define a set of marker types that can be used to refer to set points in the - * mbuf */ -__extension__ -typedef void *MARKER[0]; /**< generic marker for a point in a structure */ -__extension__ -typedef uint8_t MARKER8[0]; /**< generic marker with 1B alignment */ -__extension__ -typedef uint64_t MARKER64[0]; /**< marker that allows us to overwrite 8 bytes - * with a single assignment */ - -/** C extension macro for environments lacking C11 features. */ -#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112L -#define RTE_STD_C11 __extension__ -#else -#define RTE_STD_C11 -#endif - -/** - * The atomic counter structure. - */ -typedef struct { - volatile int16_t cnt; /**< An internal counter value. */ -} rte_atomic16_t; - -/** - * The generic rte_mbuf, containing a packet mbuf. - */ -struct rte_mbuf { - MARKER cacheline0; - - void *buf_addr; /**< Virtual address of segment buffer. */ - phys_addr_t buf_physaddr; /**< Physical address of segment buffer. */ - - uint16_t buf_len; /**< Length of segment buffer. */ - - /* next 6 bytes are initialised on RX descriptor rearm */ - MARKER8 rearm_data; - uint16_t data_off; - - /** - * 16-bit Reference counter. - * It should only be accessed using the following functions: - * rte_mbuf_refcnt_update(), rte_mbuf_refcnt_read(), and - * rte_mbuf_refcnt_set(). The functionality of these functions (atomic, - * or non-atomic) is controlled by the CONFIG_RTE_MBUF_REFCNT_ATOMIC - * config option. - */ - RTE_STD_C11 - union { - rte_atomic16_t refcnt_atomic; /**< Atomically accessed refcnt */ - uint16_t refcnt; /**< Non-atomically accessed refcnt */ - }; - uint8_t nb_segs; /**< Number of segments. */ - uint8_t port; /**< Input port. */ - - uint64_t ol_flags; /**< Offload features. */ - - /* remaining bytes are set on RX when pulling packet from descriptor */ - MARKER rx_descriptor_fields1; - - /* - * The packet type, which is the combination of outer/inner L2, L3, L4 - * and tunnel types. The packet_type is about data really present in the - * mbuf. Example: if vlan stripping is enabled, a received vlan packet - * would have RTE_PTYPE_L2_ETHER and not RTE_PTYPE_L2_VLAN because the - * vlan is stripped from the data. - */ - RTE_STD_C11 - union { - uint32_t packet_type; /**< L2/L3/L4 and tunnel information. */ - struct { - uint32_t l2_type:4; /**< (Outer) L2 type. */ - uint32_t l3_type:4; /**< (Outer) L3 type. */ - uint32_t l4_type:4; /**< (Outer) L4 type. */ - uint32_t tun_type:4; /**< Tunnel type. */ - uint32_t inner_l2_type:4; /**< Inner L2 type. */ - uint32_t inner_l3_type:4; /**< Inner L3 type. */ - uint32_t inner_l4_type:4; /**< Inner L4 type. */ - }; - }; - - uint32_t pkt_len; /**< Total pkt len: sum of all segments. */ - uint16_t data_len; /**< Amount of data in segment buffer. */ - /** VLAN TCI (CPU order), valid if PKT_RX_VLAN_STRIPPED is set. */ - uint16_t vlan_tci; - - union { - uint32_t rss; /**< RSS hash result if RSS enabled */ - struct { - RTE_STD_C11 - union { - struct { - uint16_t hash; - uint16_t id; - }; - uint32_t lo; - /**< Second 4 flexible bytes */ - }; - uint32_t hi; - /**< First 4 flexible bytes or FD ID, dependent on - PKT_RX_FDIR_* flag in ol_flags. */ - } fdir; /**< Filter identifier if FDIR enabled */ - struct { - uint32_t lo; - uint32_t hi; - } sched; /**< Hierarchical scheduler */ - uint32_t usr; /**< User defined tags. See rte_distributor_process() */ - } hash; /**< hash information */ - - uint32_t seqn; /**< Sequence number. See also rte_reorder_insert() */ - - /** Outer VLAN TCI (CPU order), valid if PKT_RX_QINQ_STRIPPED is set. */ - uint16_t vlan_tci_outer; - - /* second cache line - fields only used in slow path or on TX */ - MARKER cacheline1 __rte_cache_min_aligned; - - RTE_STD_C11 - union { - void *userdata; /**< Can be used for external metadata */ - uint64_t udata64; /**< Allow 8-byte userdata on 32-bit */ - }; - - struct rte_mempool *pool; /**< Pool from which mbuf was allocated. */ - struct rte_mbuf *next; /**< Next segment of scattered packet. */ - - /* fields to support TX offloads */ - RTE_STD_C11 - union { - uint64_t tx_offload; /**< combined for easy fetch */ - __extension__ - struct { - uint64_t l2_len:7; - /**< L2 (MAC) Header Length for non-tunneling pkt. - * Outer_L4_len + ... + Inner_L2_len for tunneling pkt. - */ - uint64_t l3_len:9; /**< L3 (IP) Header Length. */ - uint64_t l4_len:8; /**< L4 (TCP/UDP) Header Length. */ - uint64_t tso_segsz:16; /**< TCP TSO segment size */ - - /* fields for TX offloading of tunnels */ - uint64_t outer_l3_len:9; /**< Outer L3 (IP) Hdr Length. */ - uint64_t outer_l2_len:7; /**< Outer L2 (MAC) Hdr Length. */ - - /* uint64_t unused:8; */ - }; - }; - - /** Size of the application private data. In case of an indirect - * mbuf, it stores the direct mbuf private data size. */ - uint16_t priv_size; - - /** Timesync flags for use with IEEE1588. */ - uint16_t timesync; -} __rte_cache_aligned; diff --git a/bindgen-tests/tests/headers/long_double.h b/bindgen-tests/tests/headers/long_double.h index 91c4ed6ce9..c8872d6ebf 100644 --- a/bindgen-tests/tests/headers/long_double.h +++ b/bindgen-tests/tests/headers/long_double.h @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.26 +// bindgen-flags: \-\-rust-target=1.33 struct foo { long double bar; diff --git a/bindgen-tests/tests/headers/macro_const_1_0.h b/bindgen-tests/tests/headers/macro_const_1_0.h deleted file mode 100644 index 3be86b4fd2..0000000000 --- a/bindgen-tests/tests/headers/macro_const_1_0.h +++ /dev/null @@ -1,10 +0,0 @@ -// bindgen-flags: --rust-target 1.0 - -#define foo "bar" -#define CHAR 'b' -#define CHARR '\0' -#define FLOAT 5.09f -#define FLOAT_EXPR (5 / 1000.0f) -#define LONG 3L - -#define INVALID_UTF8 "\xf0\x28\x8c\x28" diff --git a/bindgen-tests/tests/headers/mangling-win32.hpp b/bindgen-tests/tests/headers/mangling-win32.hpp index 386df4aba3..76a7e664ed 100644 --- a/bindgen-tests/tests/headers/mangling-win32.hpp +++ b/bindgen-tests/tests/headers/mangling-win32.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: -- --target=i686-pc-win32 +// bindgen-flags: --raw-line '#![cfg(target = "i686-pc-windows-msvc")]' -- --target=i686-pc-win32 extern "C" void foo(); diff --git a/bindgen-tests/tests/headers/merge-extern-blocks.hpp b/bindgen-tests/tests/headers/merge_extern_blocks_post_1_82.hpp similarity index 81% rename from bindgen-tests/tests/headers/merge-extern-blocks.hpp rename to bindgen-tests/tests/headers/merge_extern_blocks_post_1_82.hpp index 392e34a390..080979f17b 100644 --- a/bindgen-tests/tests/headers/merge-extern-blocks.hpp +++ b/bindgen-tests/tests/headers/merge_extern_blocks_post_1_82.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --merge-extern-blocks --enable-cxx-namespaces -- --target=x86_64-unknown-linux +// bindgen-flags: --merge-extern-blocks --enable-cxx-namespaces --rust-target=1.82 -- --target=x86_64-unknown-linux int foo(); typedef struct Point { int x; diff --git a/bindgen-tests/tests/headers/merge_extern_blocks_pre_1_82.hpp b/bindgen-tests/tests/headers/merge_extern_blocks_pre_1_82.hpp new file mode 100644 index 0000000000..779abf174b --- /dev/null +++ b/bindgen-tests/tests/headers/merge_extern_blocks_pre_1_82.hpp @@ -0,0 +1,14 @@ +// bindgen-flags: --merge-extern-blocks --enable-cxx-namespaces --rust-target=1.81 -- --target=x86_64-unknown-linux +int foo(); +typedef struct Point { + int x; +} Point; +int bar(); + +namespace ns { + int foo(); + typedef struct Point { + int x; + } Point; + int bar(); +} diff --git a/bindgen-tests/tests/headers/namespace/nsdefine.h b/bindgen-tests/tests/headers/namespace/nsdefine.h new file mode 100644 index 0000000000..6504fa9f0a --- /dev/null +++ b/bindgen-tests/tests/headers/namespace/nsdefine.h @@ -0,0 +1,4 @@ +#pragma once + +#define BEGIN_NAMESPACE namespace repro { inline namespace __1 { +#define END_NAMESPACE } } diff --git a/bindgen-tests/tests/headers/newtype-enum.hpp b/bindgen-tests/tests/headers/newtype-enum.hpp index 890683ae85..45f3303c8c 100644 --- a/bindgen-tests/tests/headers/newtype-enum.hpp +++ b/bindgen-tests/tests/headers/newtype-enum.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --newtype-enum "Foo" --rust-target 1.28 -- -std=c++11 +// bindgen-flags: --newtype-enum "Foo" \-\-rust-target=1.33 -- -std=c++11 enum Foo { Bar = 1 << 1, diff --git a/bindgen-tests/tests/headers/newtype-global-enum.hpp b/bindgen-tests/tests/headers/newtype-global-enum.hpp index 8021a3cc72..e52b19b84a 100644 --- a/bindgen-tests/tests/headers/newtype-global-enum.hpp +++ b/bindgen-tests/tests/headers/newtype-global-enum.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --newtype-global-enum "Foo" --rust-target 1.28 -- -std=c++11 +// bindgen-flags: --newtype-global-enum "Foo" \-\-rust-target=1.33 -- -std=c++11 enum Foo { Bar = 1 << 1, diff --git a/bindgen-tests/tests/headers/opencl_vector.h b/bindgen-tests/tests/headers/opencl_vector.h new file mode 100644 index 0000000000..79022c768f --- /dev/null +++ b/bindgen-tests/tests/headers/opencl_vector.h @@ -0,0 +1,9 @@ +typedef float float4 __attribute__((ext_vector_type(4))); +typedef float float2 __attribute__((ext_vector_type(2))); + +float4 foo(float2 a, float2 b) { + float4 c; + c.xz = a; + c.yw = b; + return c; +} \ No newline at end of file diff --git a/bindgen-tests/tests/headers/operator_equals.hpp b/bindgen-tests/tests/headers/operator_equals.hpp new file mode 100644 index 0000000000..38a3a092a9 --- /dev/null +++ b/bindgen-tests/tests/headers/operator_equals.hpp @@ -0,0 +1,9 @@ +// bindgen-flags: --represent-cxx-operators --generate-inline-functions -- -x c++ +// bindgen-parse-callbacks: operator-rename + +class SomeClass { +public: + bool operator=(const SomeClass& another) { + return false; + } +}; diff --git a/bindgen-tests/tests/headers/repr-align.hpp b/bindgen-tests/tests/headers/repr-align.hpp index 3347594b5c..b3231d39bc 100644 --- a/bindgen-tests/tests/headers/repr-align.hpp +++ b/bindgen-tests/tests/headers/repr-align.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --raw-line '#![cfg(feature = "nightly")]' --rust-target 1.25 -- -std=c++11 +// bindgen-flags: --raw-line '#![cfg(feature = "nightly")]' \-\-rust-target=1.33 -- -std=c++11 struct alignas(8) a { int b; diff --git a/bindgen-tests/tests/headers/special-members.hpp b/bindgen-tests/tests/headers/special-members.hpp new file mode 100644 index 0000000000..753b2fdc0a --- /dev/null +++ b/bindgen-tests/tests/headers/special-members.hpp @@ -0,0 +1,7 @@ +class A { +public: + A(); + A(A&); + A(A&&); + ~A(); +}; \ No newline at end of file diff --git a/bindgen-tests/tests/headers/specific_receiver.hpp b/bindgen-tests/tests/headers/specific_receiver.hpp new file mode 100644 index 0000000000..a521f9f0b2 --- /dev/null +++ b/bindgen-tests/tests/headers/specific_receiver.hpp @@ -0,0 +1,7 @@ +// bindgen-flags: --use-specific-virtual-function-receiver --generate-inline-functions -- -x c++ -std=c++14 + +class Fish { +public: + virtual void swim() { + } +}; diff --git a/bindgen-tests/tests/headers/strings_array.h b/bindgen-tests/tests/headers/strings_array.h index 6a61d71049..212b0903a7 100644 --- a/bindgen-tests/tests/headers/strings_array.h +++ b/bindgen-tests/tests/headers/strings_array.h @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target=1.0 +// bindgen-flags: \-\-rust-target=1.33 const char* MY_STRING_UTF8 = "Hello, world!"; const char* MY_STRING_INTERIOR_NULL = "Hello,\0World!"; diff --git a/bindgen-tests/tests/headers/strings_cstr2.h b/bindgen-tests/tests/headers/strings_cstr2.h new file mode 100644 index 0000000000..2cd7e6222d --- /dev/null +++ b/bindgen-tests/tests/headers/strings_cstr2.h @@ -0,0 +1,5 @@ +// bindgen-flags: --rust-target=1.77 --generate-cstr + +const char* MY_STRING_UTF8 = "Hello, world!"; +const char* MY_STRING_INTERIOR_NULL = "Hello,\0World!"; +const char* MY_STRING_NON_UTF8 = "ABCDE\xFF"; diff --git a/bindgen-tests/tests/headers/strings_cstr2_2018.h b/bindgen-tests/tests/headers/strings_cstr2_2018.h new file mode 100644 index 0000000000..67d117a1bc --- /dev/null +++ b/bindgen-tests/tests/headers/strings_cstr2_2018.h @@ -0,0 +1,5 @@ +// bindgen-flags: --rust-target=1.77 --rust-edition=2018 --generate-cstr + +const char* MY_STRING_UTF8 = "Hello, world!"; +const char* MY_STRING_INTERIOR_NULL = "Hello,\0World!"; +const char* MY_STRING_NON_UTF8 = "ABCDE\xFF"; diff --git a/bindgen-tests/tests/headers/struct_with_anon_union_1_0.h b/bindgen-tests/tests/headers/struct_with_anon_union_1_0.h deleted file mode 100644 index 847c354b59..0000000000 --- a/bindgen-tests/tests/headers/struct_with_anon_union_1_0.h +++ /dev/null @@ -1,8 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -struct foo { - union { - unsigned int a; - unsigned short b; - } bar; -}; diff --git a/bindgen-tests/tests/headers/struct_with_anon_unnamed_union_1_0.h b/bindgen-tests/tests/headers/struct_with_anon_unnamed_union_1_0.h deleted file mode 100644 index 791a1593af..0000000000 --- a/bindgen-tests/tests/headers/struct_with_anon_unnamed_union_1_0.h +++ /dev/null @@ -1,8 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -struct foo { - union { - unsigned int a; - unsigned short b; - }; -}; diff --git a/bindgen-tests/tests/headers/struct_with_nesting_1_0.h b/bindgen-tests/tests/headers/struct_with_nesting_1_0.h deleted file mode 100644 index a24ae1db58..0000000000 --- a/bindgen-tests/tests/headers/struct_with_nesting_1_0.h +++ /dev/null @@ -1,19 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -struct foo { - unsigned int a; - union { - unsigned int b; - struct { - unsigned short c1; - unsigned short c2; - }; - - struct { - unsigned char d1; - unsigned char d2; - unsigned char d3; - unsigned char d4; - }; - }; -}; diff --git a/bindgen-tests/tests/headers/template-param-usage-7.hpp b/bindgen-tests/tests/headers/template-param-usage-7.hpp index 99d4cc71b4..3d70cee145 100644 --- a/bindgen-tests/tests/headers/template-param-usage-7.hpp +++ b/bindgen-tests/tests/headers/template-param-usage-7.hpp @@ -6,5 +6,5 @@ class DoesNotUseU { V v; }; -// The bool should go away becuase U is not used. +// The bool should go away because U is not used. using Alias = DoesNotUseU; diff --git a/bindgen-tests/tests/headers/transform-op.hpp b/bindgen-tests/tests/headers/transform-op.hpp index aa6118eb67..907a5a4657 100644 --- a/bindgen-tests/tests/headers/transform-op.hpp +++ b/bindgen-tests/tests/headers/transform-op.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.0 -- -std=c++11 +// bindgen-flags: \-\-rust-target=1.33 -- -std=c++11 typedef unsigned char uint8_t; typedef int int32_t; diff --git a/bindgen-tests/tests/headers/typeref_1_0.hpp b/bindgen-tests/tests/headers/typeref_1_0.hpp deleted file mode 100644 index 70dfc11fb1..0000000000 --- a/bindgen-tests/tests/headers/typeref_1_0.hpp +++ /dev/null @@ -1,30 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -struct nsFoo; - -namespace mozilla { - -struct FragmentOrURL { bool mIsLocalRef; }; -struct Position { }; - -} // namespace mozilla - -class Bar { - nsFoo* mFoo; -}; - -namespace mozilla { - -template -struct StyleShapeSource { - union { - Position* mPosition; - FragmentOrURL* mFragmentOrURL; - }; -}; - -} // namespace mozilla - -struct nsFoo { - mozilla::StyleShapeSource mBar; -}; diff --git a/bindgen-tests/tests/headers/uncallable_functions.hpp b/bindgen-tests/tests/headers/uncallable_functions.hpp new file mode 100644 index 0000000000..9187470c65 --- /dev/null +++ b/bindgen-tests/tests/headers/uncallable_functions.hpp @@ -0,0 +1,9 @@ +// bindgen-flags: --generate-deleted-functions --generate-private-functions --generate-pure-virtual-functions --generate-inline-functions -- -x c++ -std=c++14 + +class Test { +public: + virtual void a() = 0; + void b() = delete; +private: + void c() {} +}; diff --git a/bindgen-tests/tests/headers/union-align.h b/bindgen-tests/tests/headers/union-align.h index 9557b2798a..bfb5b5a199 100644 --- a/bindgen-tests/tests/headers/union-align.h +++ b/bindgen-tests/tests/headers/union-align.h @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.26 +// bindgen-flags: \-\-rust-target=1.33 union Bar { unsigned char foo; diff --git a/bindgen-tests/tests/headers/union-in-ns_1_0.hpp b/bindgen-tests/tests/headers/union-in-ns_1_0.hpp deleted file mode 100644 index f3ae221057..0000000000 --- a/bindgen-tests/tests/headers/union-in-ns_1_0.hpp +++ /dev/null @@ -1,5 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --enable-cxx-namespaces - -union bar { - int baz; -}; diff --git a/bindgen-tests/tests/headers/union_bitfield_1_0.h b/bindgen-tests/tests/headers/union_bitfield_1_0.h deleted file mode 100644 index 06b61ad771..0000000000 --- a/bindgen-tests/tests/headers/union_bitfield_1_0.h +++ /dev/null @@ -1,14 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq --impl-partialeq - -union U4 { - unsigned derp : 1; -}; - -union B { - unsigned foo : 31; - unsigned char bar : 1; -}; - -union HasBigBitfield { - __int128 x : 128; -}; diff --git a/bindgen-tests/tests/headers/union_dtor_1_0.hpp b/bindgen-tests/tests/headers/union_dtor_1_0.hpp deleted file mode 100644 index 01f7636671..0000000000 --- a/bindgen-tests/tests/headers/union_dtor_1_0.hpp +++ /dev/null @@ -1,7 +0,0 @@ -// bindgen-flags: --rust-target 1.0 - -union UnionWithDtor { - ~UnionWithDtor(); - int mFoo; - void* mBar; -}; diff --git a/bindgen-tests/tests/headers/union_fields_1_0.hpp b/bindgen-tests/tests/headers/union_fields_1_0.hpp deleted file mode 100644 index bbb67fbc6e..0000000000 --- a/bindgen-tests/tests/headers/union_fields_1_0.hpp +++ /dev/null @@ -1,7 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -typedef union { - int mInt; - float mFloat; - void* mPointer; -} nsStyleUnion; diff --git a/bindgen-tests/tests/headers/union_template_1_0.hpp b/bindgen-tests/tests/headers/union_template_1_0.hpp deleted file mode 100644 index 18e3d74a37..0000000000 --- a/bindgen-tests/tests/headers/union_template_1_0.hpp +++ /dev/null @@ -1,21 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -template -struct NastyStruct { - bool mIsSome; - union { - void* mFoo; - unsigned long mDummy; - } mStorage; - - union { - short wat; - int* wut; - }; -}; - -template -union Whatever { - void* mTPtr; - int mInt; -}; diff --git a/bindgen-tests/tests/headers/union_with_anon_struct_1_0.h b/bindgen-tests/tests/headers/union_with_anon_struct_1_0.h deleted file mode 100644 index 9313299eb0..0000000000 --- a/bindgen-tests/tests/headers/union_with_anon_struct_1_0.h +++ /dev/null @@ -1,8 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -union foo { - struct { - unsigned int a; - unsigned int b; - } bar; -}; diff --git a/bindgen-tests/tests/headers/union_with_anon_struct_bitfield_1_0.h b/bindgen-tests/tests/headers/union_with_anon_struct_bitfield_1_0.h deleted file mode 100644 index 0b0e3d7371..0000000000 --- a/bindgen-tests/tests/headers/union_with_anon_struct_bitfield_1_0.h +++ /dev/null @@ -1,9 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -union foo { - int a; - struct { - int b : 7; - int c : 25; - }; -}; diff --git a/bindgen-tests/tests/headers/union_with_anon_union_1_0.h b/bindgen-tests/tests/headers/union_with_anon_union_1_0.h deleted file mode 100644 index 28a7231dbf..0000000000 --- a/bindgen-tests/tests/headers/union_with_anon_union_1_0.h +++ /dev/null @@ -1,8 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -union foo { - union { - unsigned int a; - unsigned short b; - } bar; -}; diff --git a/bindgen-tests/tests/headers/union_with_anon_unnamed_struct_1_0.h b/bindgen-tests/tests/headers/union_with_anon_unnamed_struct_1_0.h deleted file mode 100644 index 506a41f661..0000000000 --- a/bindgen-tests/tests/headers/union_with_anon_unnamed_struct_1_0.h +++ /dev/null @@ -1,11 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -union pixel { - unsigned int rgba; - struct { - unsigned char r; - unsigned char g; - unsigned char b; - unsigned char a; - }; -}; diff --git a/bindgen-tests/tests/headers/union_with_anon_unnamed_union_1_0.h b/bindgen-tests/tests/headers/union_with_anon_unnamed_union_1_0.h deleted file mode 100644 index c556a61311..0000000000 --- a/bindgen-tests/tests/headers/union_with_anon_unnamed_union_1_0.h +++ /dev/null @@ -1,9 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -union foo { - unsigned int a; - union { - unsigned short b; - unsigned char c; - }; -}; diff --git a/bindgen-tests/tests/headers/union_with_big_member_1_0.h b/bindgen-tests/tests/headers/union_with_big_member_1_0.h deleted file mode 100644 index 0429435478..0000000000 --- a/bindgen-tests/tests/headers/union_with_big_member_1_0.h +++ /dev/null @@ -1,16 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -union WithBigArray { - int a; - int b[33]; -}; - -union WithBigArray2 { - int a; - char b[33]; -}; - -union WithBigMember { - int a; - union WithBigArray b; -}; diff --git a/bindgen-tests/tests/headers/union_with_nesting_1_0.h b/bindgen-tests/tests/headers/union_with_nesting_1_0.h deleted file mode 100644 index 3cdb7238bc..0000000000 --- a/bindgen-tests/tests/headers/union_with_nesting_1_0.h +++ /dev/null @@ -1,16 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --with-derive-hash --with-derive-partialeq --with-derive-eq - -union foo { - unsigned int a; - struct { - union { - unsigned short b1; - unsigned short b2; - }; - - union { - unsigned short c1; - unsigned short c2; - }; - }; -}; diff --git a/bindgen-tests/tests/headers/union_with_zero_sized_array.h b/bindgen-tests/tests/headers/union_with_zero_sized_array.h new file mode 100644 index 0000000000..ace745f26c --- /dev/null +++ b/bindgen-tests/tests/headers/union_with_zero_sized_array.h @@ -0,0 +1,5 @@ +union U { + char d0[0]; + char d1[1]; + char d2[2]; +}; diff --git a/bindgen-tests/tests/headers/use-core_1_0.h b/bindgen-tests/tests/headers/use-core_1_0.h deleted file mode 100644 index 40de9d158d..0000000000 --- a/bindgen-tests/tests/headers/use-core_1_0.h +++ /dev/null @@ -1,13 +0,0 @@ -// bindgen-flags: --rust-target 1.0 --use-core --raw-line "extern crate core;" --with-derive-hash --with-derive-partialeq --with-derive-eq - -struct foo { - int a, b; - void* bar; -}; - -union { - int bar; - long baz; -} bazz; - -typedef void (*fooFunction)(int bar); diff --git a/bindgen-tests/tests/headers/va_list_aarch64_linux.h b/bindgen-tests/tests/headers/va_list_aarch64_linux.h new file mode 100644 index 0000000000..7d2206a76e --- /dev/null +++ b/bindgen-tests/tests/headers/va_list_aarch64_linux.h @@ -0,0 +1,4 @@ +// bindgen-flags: -- --target=aarch64-unknown-linux-gnu + +typedef __builtin_va_list va_list; +int vprintf(const char* format, va_list vlist); diff --git a/bindgen-tests/tests/headers/win32-dtors.hpp b/bindgen-tests/tests/headers/win32-dtors.hpp index dc9b0fdc6e..7faa5e9562 100644 --- a/bindgen-tests/tests/headers/win32-dtors.hpp +++ b/bindgen-tests/tests/headers/win32-dtors.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.0 -- --target=x86_64-pc-windows-msvc +// bindgen-flags: \-\-rust-target=1.33 -- --target=x86_64-pc-windows-msvc struct CppObj { int x; diff --git a/bindgen-tests/tests/headers/win32-thiscall.hpp b/bindgen-tests/tests/headers/win32-thiscall.hpp new file mode 100644 index 0000000000..d4e3976303 --- /dev/null +++ b/bindgen-tests/tests/headers/win32-thiscall.hpp @@ -0,0 +1,7 @@ +// bindgen-flags: \-\-rust-target=1.33 -- --target=i686-pc-windows-msvc + +class Foo { + public: + void test(); + int test2(int var); +}; diff --git a/bindgen-tests/tests/headers/win32-thiscall_1_0.hpp b/bindgen-tests/tests/headers/win32-thiscall_1_0.hpp deleted file mode 100644 index 5907c76eaf..0000000000 --- a/bindgen-tests/tests/headers/win32-thiscall_1_0.hpp +++ /dev/null @@ -1,7 +0,0 @@ -// bindgen-flags: --rust-target 1.0 -- --target=i686-pc-windows-msvc - -class Foo { - public: - void test(); - int test2(int var); -}; diff --git a/bindgen-tests/tests/headers/win32-vectorcall-1_0.h b/bindgen-tests/tests/headers/win32-vectorcall-1_0.h deleted file mode 100644 index a1f852b52f..0000000000 --- a/bindgen-tests/tests/headers/win32-vectorcall-1_0.h +++ /dev/null @@ -1,3 +0,0 @@ -// bindgen-flags: --rust-target 1.0 -- --target=x86_64-pc-windows-msvc - -int __vectorcall test_vectorcall(int a, int b); diff --git a/bindgen-tests/tests/headers/win32-vectorcall.h b/bindgen-tests/tests/headers/win32-vectorcall.h new file mode 100644 index 0000000000..245d97b340 --- /dev/null +++ b/bindgen-tests/tests/headers/win32-vectorcall.h @@ -0,0 +1,3 @@ +// bindgen-flags: \-\-rust-target=1.33 -- --target=x86_64-pc-windows-msvc + +int __vectorcall test_vectorcall(int a, int b); diff --git a/bindgen-tests/tests/headers/wrap-static-fns.h b/bindgen-tests/tests/headers/wrap-static-fns.h index 131b7ab15f..5cd3d41aee 100644 --- a/bindgen-tests/tests/headers/wrap-static-fns.h +++ b/bindgen-tests/tests/headers/wrap-static-fns.h @@ -1,7 +1,7 @@ -// bindgen-flags: --experimental --wrap-static-fns +// bindgen-flags: --wrap-static-fns // bindgen-parse-callbacks: wrap-as-variadic-fn -// to avoid poluting theexpectation tests we put the stdarg.h behind a conditional +// to avoid polluting the expectation tests we put the stdarg.h behind a conditional // variable only used in bindgen-integration #ifdef USE_VA_HEADER #include diff --git a/bindgen-tests/tests/headers/wrap_unsafe_ops_anon_union_1_0.hpp b/bindgen-tests/tests/headers/wrap_unsafe_ops_anon_union.hpp similarity index 82% rename from bindgen-tests/tests/headers/wrap_unsafe_ops_anon_union_1_0.hpp rename to bindgen-tests/tests/headers/wrap_unsafe_ops_anon_union.hpp index 3b595f2ea7..e44b43285a 100644 --- a/bindgen-tests/tests/headers/wrap_unsafe_ops_anon_union_1_0.hpp +++ b/bindgen-tests/tests/headers/wrap_unsafe_ops_anon_union.hpp @@ -1,4 +1,4 @@ -// bindgen-flags: --rust-target 1.0 --wrap-unsafe-ops --no-layout-tests +// bindgen-flags: \-\-rust-target=1.33 --wrap-unsafe-ops --no-layout-tests template struct TErrorResult { diff --git a/bindgen-tests/tests/headers/wrap_unsafe_ops_dynamic_loading_simple.h b/bindgen-tests/tests/headers/wrap_unsafe_ops_dynamic_loading_simple.h index 2b8c107185..36a638ae2a 100644 --- a/bindgen-tests/tests/headers/wrap_unsafe_ops_dynamic_loading_simple.h +++ b/bindgen-tests/tests/headers/wrap_unsafe_ops_dynamic_loading_simple.h @@ -3,3 +3,5 @@ int foo(int x, int y); int bar(void *x); int baz(); + +const int FLUX; diff --git a/bindgen-tests/tests/macro_fallback_test_headers/another_header.h b/bindgen-tests/tests/macro_fallback_test_headers/another_header.h new file mode 100644 index 0000000000..b0c40eb43f --- /dev/null +++ b/bindgen-tests/tests/macro_fallback_test_headers/another_header.h @@ -0,0 +1,10 @@ +#ifndef ANOTHER_HEADER_H +#define ANOTHER_HEADER_H + +#include + +#define SHOULD_NOT_GENERATE UINT64_C(~0) +#define MY_CONST UINT32_C(69) +#define NEGATIVE ~0 + +#endif diff --git a/bindgen-tests/tests/macro_fallback_test_headers/one_header.h b/bindgen-tests/tests/macro_fallback_test_headers/one_header.h new file mode 100644 index 0000000000..5058814bba --- /dev/null +++ b/bindgen-tests/tests/macro_fallback_test_headers/one_header.h @@ -0,0 +1,8 @@ +#ifndef ONE_HEADER_H +#define ONE_HEADER_H + +#include + +#define THE_CONST UINT32_C(28) + +#endif diff --git a/bindgen-tests/tests/parse_callbacks/item_discovery_callback/header_item_discovery.h b/bindgen-tests/tests/parse_callbacks/item_discovery_callback/header_item_discovery.h new file mode 100644 index 0000000000..eb44e5fc58 --- /dev/null +++ b/bindgen-tests/tests/parse_callbacks/item_discovery_callback/header_item_discovery.h @@ -0,0 +1,32 @@ +// Structs +void function_using_anonymous_struct(struct {} arg0); + +struct NamedStruct { +}; + +typedef struct NamedStruct AliasOfNamedStruct; + + +// Unions +void function_using_anonymous_union(union {} arg0); + +union NamedUnion { +}; + +typedef union NamedUnion AliasOfNamedUnion; + +// Enums + +// We don't include an anonymous enum because such enums +// are not visible outside the function, and thus tend not +// to be useful - bindgen doesn't handle them for this reason. + +enum NamedEnum { + Fish, +}; + +typedef enum NamedEnum AliasOfNamedEnum; + +// Functions + +void named_function(); diff --git a/bindgen-tests/tests/parse_callbacks/item_discovery_callback/header_item_discovery.hpp b/bindgen-tests/tests/parse_callbacks/item_discovery_callback/header_item_discovery.hpp new file mode 100644 index 0000000000..1de8d99e4d --- /dev/null +++ b/bindgen-tests/tests/parse_callbacks/item_discovery_callback/header_item_discovery.hpp @@ -0,0 +1,6 @@ +// Methods + +class SomeClass { +public: + void named_method(); +}; \ No newline at end of file diff --git a/bindgen-tests/tests/parse_callbacks/item_discovery_callback/mod.rs b/bindgen-tests/tests/parse_callbacks/item_discovery_callback/mod.rs new file mode 100644 index 0000000000..6a6d0149f5 --- /dev/null +++ b/bindgen-tests/tests/parse_callbacks/item_discovery_callback/mod.rs @@ -0,0 +1,377 @@ +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use regex::Regex; + +use bindgen::callbacks::{DiscoveredItem, DiscoveredItemId, ParseCallbacks}; +use bindgen::Builder; + +#[derive(Debug, Default)] +struct ItemDiscovery(Rc>); + +pub type ItemCache = HashMap; + +impl ParseCallbacks for ItemDiscovery { + fn new_item_found(&self, _id: DiscoveredItemId, _item: DiscoveredItem) { + self.0.borrow_mut().insert(_id, _item); + } +} + +fn test_item_discovery_callback( + header: &str, + expected: &HashMap, +) { + let discovery = ItemDiscovery::default(); + let info = Rc::clone(&discovery.0); + + let mut header_path = env!("CARGO_MANIFEST_DIR").to_string(); + header_path.push_str(header); + + Builder::default() + .header(header_path) + .parse_callbacks(Box::new(discovery)) + .generate() + .expect("TODO: panic message"); + + compare_item_caches(&info.borrow(), expected); +} + +#[test] +fn test_item_discovery_callback_c() { + let expected = ItemCache::from([ + ( + DiscoveredItemId::new(10), + DiscoveredItem::Struct { + original_name: Some("NamedStruct".to_string()), + final_name: "NamedStruct".to_string(), + }, + ), + ( + DiscoveredItemId::new(11), + DiscoveredItem::Alias { + alias_name: "AliasOfNamedStruct".to_string(), + alias_for: DiscoveredItemId::new(10), + }, + ), + ( + DiscoveredItemId::new(20), + DiscoveredItem::Union { + original_name: Some("NamedUnion".to_string()), + final_name: "NamedUnion".to_string(), + }, + ), + ( + DiscoveredItemId::new(21), + DiscoveredItem::Alias { + alias_name: "AliasOfNamedUnion".to_string(), + alias_for: DiscoveredItemId::new(20), + }, + ), + ( + DiscoveredItemId::new(27), + DiscoveredItem::Alias { + alias_name: "AliasOfNamedEnum".to_string(), + alias_for: DiscoveredItemId::new(24), + }, + ), + ( + DiscoveredItemId::new(24), + DiscoveredItem::Enum { + final_name: "NamedEnum".to_string(), + }, + ), + ( + DiscoveredItemId::new(30), + DiscoveredItem::Struct { + original_name: None, + final_name: "_bindgen_ty_*".to_string(), + }, + ), + ( + DiscoveredItemId::new(40), + DiscoveredItem::Union { + original_name: None, + final_name: "_bindgen_ty_*".to_string(), + }, + ), + ( + DiscoveredItemId::new(41), + DiscoveredItem::Function { + final_name: "named_function".to_string(), + }, + ), + ]); + test_item_discovery_callback( + "/tests/parse_callbacks/item_discovery_callback/header_item_discovery.h", &expected); +} + +#[test] +fn test_item_discovery_callback_cpp() { + let expected = ItemCache::from([ + ( + DiscoveredItemId::new(1), + DiscoveredItem::Struct { + original_name: Some("SomeClass".to_string()), + final_name: "SomeClass".to_string(), + }, + ), + ( + DiscoveredItemId::new(2), + DiscoveredItem::Method { + final_name: "named_method".to_string(), + parent: DiscoveredItemId::new(1), + }, + ), + ]); + test_item_discovery_callback( + "/tests/parse_callbacks/item_discovery_callback/header_item_discovery.hpp", &expected); +} + +pub fn compare_item_caches(generated: &ItemCache, expected: &ItemCache) { + // We can't use a simple Eq::eq comparison because of two reasons: + // - anonymous structs/unions will have a final name generated by bindgen which may change + // if the header file or the bindgen logic is altered + // - aliases have a DiscoveredItemId that we can't directly compare for the same instability reasons + for expected_item in expected.values() { + let found = generated.iter().find(|(_generated_id, generated_item)| { + compare_item_info( + expected_item, + generated_item, + expected, + generated, + ) + }); + + assert!( + found.is_some(), + "Missing Expected Item: {expected_item:#?}\n in {generated:#?}" + ); + } +} + +fn compare_item_info( + expected_item: &DiscoveredItem, + generated_item: &DiscoveredItem, + expected: &ItemCache, + generated: &ItemCache, +) -> bool { + if std::mem::discriminant(expected_item) != + std::mem::discriminant(generated_item) + { + return false; + } + + match generated_item { + DiscoveredItem::Struct { .. } => { + compare_struct_info(expected_item, generated_item) + } + DiscoveredItem::Union { .. } => { + compare_union_info(expected_item, generated_item) + } + DiscoveredItem::Alias { .. } => compare_alias_info( + expected_item, + generated_item, + expected, + generated, + ), + DiscoveredItem::Enum { .. } => { + compare_enum_info(expected_item, generated_item) + } + DiscoveredItem::Function { .. } => { + compare_function_info(expected_item, generated_item) + } + DiscoveredItem::Method { .. } => { + compare_method_info(expected_item, generated_item) + } + } +} + +pub fn compare_names(expected_name: &str, generated_name: &str) -> bool { + if let Ok(regex) = Regex::new(expected_name) { + regex.is_match(generated_name) + } else { + false + } +} + +pub fn compare_struct_info( + expected_item: &DiscoveredItem, + generated_item: &DiscoveredItem, +) -> bool { + let DiscoveredItem::Struct { + original_name: expected_original_name, + final_name: expected_final_name, + } = expected_item + else { + unreachable!() + }; + + let DiscoveredItem::Struct { + original_name: generated_original_name, + final_name: generated_final_name, + } = generated_item + else { + unreachable!() + }; + + if !compare_names(expected_final_name, generated_final_name) { + return false; + } + + match (expected_original_name, generated_original_name) { + (None, None) => true, + (Some(expected_original_name), Some(generated_original_name)) => { + compare_names(expected_original_name, generated_original_name) + } + _ => false, + } +} + +pub fn compare_union_info( + expected_item: &DiscoveredItem, + generated_item: &DiscoveredItem, +) -> bool { + let DiscoveredItem::Union { + original_name: expected_original_name, + final_name: expected_final_name, + } = expected_item + else { + unreachable!() + }; + + let DiscoveredItem::Union { + original_name: generated_original_name, + final_name: generated_final_name, + } = generated_item + else { + unreachable!() + }; + + if !compare_names(expected_final_name, generated_final_name) { + return false; + } + + match (expected_original_name, generated_original_name) { + (None, None) => true, + (Some(expected_original_name), Some(generated_original_name)) => { + compare_names(expected_original_name, generated_original_name) + } + _ => false, + } +} + +pub fn compare_enum_info( + expected_item: &DiscoveredItem, + generated_item: &DiscoveredItem, +) -> bool { + let DiscoveredItem::Enum { + final_name: expected_final_name, + } = expected_item + else { + unreachable!() + }; + + let DiscoveredItem::Enum { + final_name: generated_final_name, + } = generated_item + else { + unreachable!() + }; + + if !compare_names(expected_final_name, generated_final_name) { + return false; + } + true +} + +pub fn compare_alias_info( + expected_item: &DiscoveredItem, + generated_item: &DiscoveredItem, + expected: &ItemCache, + generated: &ItemCache, +) -> bool { + let DiscoveredItem::Alias { + alias_name: expected_alias_name, + alias_for: expected_alias_for, + } = expected_item + else { + unreachable!() + }; + + let DiscoveredItem::Alias { + alias_name: generated_alias_name, + alias_for: generated_alias_for, + } = generated_item + else { + unreachable!() + }; + + if !compare_names(expected_alias_name, generated_alias_name) { + return false; + } + + // Assumes correct test definition + let expected_aliased = expected.get(expected_alias_for).unwrap(); + + // We must have the aliased type in the cache + let Some(generated_aliased) = generated.get(generated_alias_for) else { + return false; + }; + + compare_item_info(expected_aliased, generated_aliased, expected, generated) +} + +pub fn compare_function_info( + expected_item: &DiscoveredItem, + generated_item: &DiscoveredItem, +) -> bool { + let DiscoveredItem::Function { + final_name: expected_final_name, + } = expected_item + else { + unreachable!() + }; + + let DiscoveredItem::Function { + final_name: generated_final_name, + } = generated_item + else { + unreachable!() + }; + + if !compare_names(expected_final_name, generated_final_name) { + return false; + } + true +} + +pub fn compare_method_info( + expected_item: &DiscoveredItem, + generated_item: &DiscoveredItem, +) -> bool { + let DiscoveredItem::Method { + final_name: expected_final_name, + parent: expected_parent, + } = expected_item + else { + unreachable!() + }; + + let DiscoveredItem::Method { + final_name: generated_final_name, + parent: generated_parent, + } = generated_item + else { + unreachable!() + }; + + if expected_parent != generated_parent { + return false; + } + + if !compare_names(expected_final_name, generated_final_name) { + return false; + } + true +} diff --git a/bindgen-tests/tests/parse_callbacks/mod.rs b/bindgen-tests/tests/parse_callbacks/mod.rs index ee31d56e49..5fe8d90d4c 100644 --- a/bindgen-tests/tests/parse_callbacks/mod.rs +++ b/bindgen-tests/tests/parse_callbacks/mod.rs @@ -1,3 +1,5 @@ +mod item_discovery_callback; + use bindgen::callbacks::*; use bindgen::FieldVisibilityKind; @@ -52,7 +54,7 @@ impl ParseCallbacks for PrefixLinkNameParseCallback { ) -> Option { self.prefix .as_deref() - .map(|prefix| format!("{}{}", prefix, item_info.name)) + .map(|prefix| format!("{prefix}{}", item_info.name)) } } @@ -66,7 +68,7 @@ impl ParseCallbacks for EnumVariantRename { original_variant_name: &str, _variant_value: EnumVariantValue, ) -> Option { - Some(format!("RENAMED_{}", original_variant_name)) + Some(format!("RENAMED_{original_variant_name}")) } } @@ -93,8 +95,8 @@ struct FieldVisibility { } /// Implements the `field_visibility` function of the trait by checking if the -/// field name starts with `private_`. If it does it makes it private, if it -/// doesn't it makes it public, taking into account the default visibility. +/// field name starts with `private_`. If it does, it makes it private, if it +/// doesn't, it makes it public, taking into account the default visibility. impl ParseCallbacks for FieldVisibility { fn field_visibility( &self, @@ -113,6 +115,28 @@ impl ParseCallbacks for FieldVisibility { } } +#[derive(Debug)] +struct TypeVisibility; + +/// Implements the `field_visibility` function of the trait by checking the +/// type name. Depending on name prefix, it will return a different visibility. +impl ParseCallbacks for TypeVisibility { + fn field_visibility( + &self, + FieldInfo { type_name, .. }: FieldInfo, + ) -> Option { + if type_name.starts_with("private_") { + Some(FieldVisibilityKind::Private) + } else if type_name.starts_with("pubcrate_") { + Some(FieldVisibilityKind::PublicCrate) + } else if type_name.starts_with("pub_") { + Some(FieldVisibilityKind::Public) + } else { + None + } + } +} + #[derive(Debug)] pub(super) struct WrapAsVariadicFn; @@ -122,6 +146,19 @@ impl ParseCallbacks for WrapAsVariadicFn { } } +#[derive(Debug)] +pub(super) struct OperatorRename; + +impl ParseCallbacks for OperatorRename { + fn generated_name_override(&self, info: ItemInfo) -> Option { + if info.name == "operator=" { + Some("operatorequals".to_string()) + } else { + None + } + } +} + pub fn lookup(cb: &str) -> Box { match cb { "enum-variant-rename" => Box::new(EnumVariantRename), @@ -129,6 +166,8 @@ pub fn lookup(cb: &str) -> Box { Box::new(BlocklistedTypeImplementsTrait) } "wrap-as-variadic-fn" => Box::new(WrapAsVariadicFn), + "type-visibility" => Box::new(TypeVisibility), + "operator-rename" => Box::new(OperatorRename), call_back => { if let Some(prefix) = call_back.strip_prefix("remove-function-prefix-") @@ -149,7 +188,7 @@ pub fn lookup(cb: &str) -> Box { ), }) } else { - panic!("Couldn't find name ParseCallbacks: {}", cb) + panic!("Couldn't find name ParseCallbacks: {cb}") } } } diff --git a/bindgen-tests/tests/quickchecking/Cargo.toml b/bindgen-tests/tests/quickchecking/Cargo.toml index 294961baf9..b26ba3b392 100644 --- a/bindgen-tests/tests/quickchecking/Cargo.toml +++ b/bindgen-tests/tests/quickchecking/Cargo.toml @@ -1,10 +1,12 @@ +lints.workspace = true + [package] name = "quickchecking" description = "Bindgen property tests with quickcheck. Generate random valid C code and pass it to the csmith/predicate.py script" version = "0.0.0" publish = false -rust-version = "1.64" -edition = "2018" +rust-version.workspace = true +edition.workspace = true [lib] name = "quickchecking" @@ -15,10 +17,9 @@ name = "quickchecking" path = "src/bin.rs" [dependencies] -clap = "4" -lazy_static = "1.0" -quickcheck = "1.0" -tempfile = "3" +clap.workspace = true +quickcheck.workspace = true +tempfile.workspace = true [features] # No features by default. diff --git a/bindgen-tests/tests/quickchecking/src/bin.rs b/bindgen-tests/tests/quickchecking/src/bin.rs index 7f1307e15f..3072bc7b46 100644 --- a/bindgen-tests/tests/quickchecking/src/bin.rs +++ b/bindgen-tests/tests/quickchecking/src/bin.rs @@ -14,8 +14,6 @@ //! ``` //! #![deny(missing_docs)] -extern crate clap; -extern crate quickchecking; use clap::{Arg, ArgAction, Command}; use std::path::PathBuf; @@ -43,9 +41,10 @@ fn parse_tests_count(v: &str) -> Result { // Parse CLI argument input for fuzzed headers output path. fn parse_path(v: &str) -> Result { let path = PathBuf::from(v); - match path.is_dir() { - true => Ok(path), - false => Err(String::from("Provided directory path does not exist.")), + if path.is_dir() { + Ok(path) + } else { + Err(String::from("Provided directory path does not exist.")) } } @@ -107,5 +106,5 @@ fn main() { let generate_range = *matches.get_one::("range").unwrap(); let tests = *matches.get_one::("count").unwrap(); - quickchecking::test_bindgen(generate_range, tests, output_path) + quickchecking::test_bindgen(generate_range, tests, output_path); } diff --git a/bindgen-tests/tests/quickchecking/src/fuzzers.rs b/bindgen-tests/tests/quickchecking/src/fuzzers.rs index 569ed6e09b..176636f66f 100644 --- a/bindgen-tests/tests/quickchecking/src/fuzzers.rs +++ b/bindgen-tests/tests/quickchecking/src/fuzzers.rs @@ -1,7 +1,8 @@ use quickcheck::{Arbitrary, Gen}; use std::fmt; +use std::fmt::Write as _; -/// BaseTypeC is used in generation of C headers to represent the C language's +/// `BaseTypeC` is used in generation of C headers to represent the C language's /// primitive types as well as `void*`. #[derive(Debug, Clone)] pub struct BaseTypeC { @@ -9,7 +10,7 @@ pub struct BaseTypeC { pub def: String, } -/// TypeQualifierC is used in generation of C headers to represent qualifiers +/// `TypeQualifierC` is used in generation of C headers to represent qualifiers /// such as `const`. #[derive(Debug, Clone)] pub struct TypeQualifierC { @@ -17,7 +18,7 @@ pub struct TypeQualifierC { pub def: String, } -/// PointerLevelC is used in generation of C headers to represent number of +/// `PointerLevelC` is used in generation of C headers to represent number of /// `*` for pointer types. #[derive(Debug, Clone)] pub struct PointerLevelC { @@ -25,7 +26,7 @@ pub struct PointerLevelC { pub def: String, } -/// ArrayDimensionC is used in generation of C headers to represent number of +/// `ArrayDimensionC` is used in generation of C headers to represent number of /// `[]` used to define array types. #[derive(Debug, Clone)] pub struct ArrayDimensionC { @@ -33,7 +34,7 @@ pub struct ArrayDimensionC { pub def: String, } -/// BasicTypeDeclarationC is used in generation of C headers to represent +/// `BasicTypeDeclarationC` is used in generation of C headers to represent /// declarations outside of function pointers that take the form /// `BaseTypeC` + `TypeQualifierC` + `PointerLevelC` + `ident_id`. #[derive(Debug, Clone)] @@ -46,11 +47,11 @@ pub struct BasicTypeDeclarationC { pub pointer_level: PointerLevelC, /// The declaration's array dimension, i.e. [][][]. pub array_dimension: ArrayDimensionC, - /// The declaration's identifier, i.e. ident_N. + /// The declaration's identifier, i.e. `ident_N`. pub ident_id: String, } -/// StructDeclarationC is used in generation of C headers to represent the +/// `StructDeclarationC` is used in generation of C headers to represent the /// definition of a struct type. #[derive(Debug, Clone)] pub struct StructDeclarationC { @@ -58,11 +59,11 @@ pub struct StructDeclarationC { pub fields: DeclarationListC, /// The declaration's array dimension, i.e. [][][]. pub array_dimension: ArrayDimensionC, - /// The declaration's identifier, i.e. struct_N. + /// The declaration's identifier, i.e. `struct_N`. pub ident_id: String, } -/// UnionDeclarationC is used in generation of C headers to represent the +/// `UnionDeclarationC` is used in generation of C headers to represent the /// definition of a union type. #[derive(Debug, Clone)] pub struct UnionDeclarationC { @@ -70,11 +71,11 @@ pub struct UnionDeclarationC { pub fields: DeclarationListC, /// The declaration's array dimension, i.e. [][][]. pub array_dimension: ArrayDimensionC, - /// The declaration's identifier, i.e. union_N. + /// The declaration's identifier, i.e. `union_N`. pub ident_id: String, } -/// FunctionPointerDeclarationC is used in generation of C headers to represent +/// `FunctionPointerDeclarationC` is used in generation of C headers to represent /// the definition of a function pointer type. #[derive(Debug, Clone)] pub struct FunctionPointerDeclarationC { @@ -86,11 +87,11 @@ pub struct FunctionPointerDeclarationC { pub pointer_level: PointerLevelC, /// The function's parameters. pub params: ParameterListC, - /// The declaration's identifier, i.e. func_ptr_N. + /// The declaration's identifier, i.e. `func_ptr_N`. pub ident_id: String, } -/// FunctionPrototypeC is used in generation of C headers to represent the +/// `FunctionPrototypeC` is used in generation of C headers to represent the /// definition of a function prototype. #[derive(Debug, Clone)] pub struct FunctionPrototypeC { @@ -106,7 +107,7 @@ pub struct FunctionPrototypeC { pub ident_id: String, } -/// ParameterC is used in generation of C headers to represent the +/// `ParameterC` is used in generation of C headers to represent the /// definition function parameters. #[derive(Debug, Clone)] pub struct ParameterC { @@ -118,7 +119,7 @@ pub struct ParameterC { pub pointer_level: PointerLevelC, } -/// ParameterListC is used in generation of C headers to represent a list of +/// `ParameterListC` is used in generation of C headers to represent a list of /// definitions of function parameters. #[derive(Debug, Clone)] pub struct ParameterListC { @@ -126,7 +127,7 @@ pub struct ParameterListC { pub params: Vec, } -/// DeclarationC is used in generation of C headers to represent all supported +/// `DeclarationC` is used in generation of C headers to represent all supported /// C type declarations allowed in the generated header. #[derive(Debug, Clone)] pub enum DeclarationC { @@ -142,7 +143,7 @@ pub enum DeclarationC { VariableDecl(BasicTypeDeclarationC), } -/// DeclarationListC is used in generation of C headers to represent a list of +/// `DeclarationListC` is used in generation of C headers to represent a list of /// declarations. #[derive(Debug, Clone)] pub struct DeclarationListC { @@ -150,7 +151,7 @@ pub struct DeclarationListC { pub decls: Vec, } -/// HeaderC is used in generation of C headers to represent a collection of +/// `HeaderC` is used in generation of C headers to represent a collection of /// declarations. #[derive(Clone)] pub struct HeaderC { @@ -158,13 +159,13 @@ pub struct HeaderC { pub def: DeclarationListC, } -/// MakeUnique is used in generation of C headers to make declaration +/// `MakeUnique` is used in generation of C headers to make declaration /// identifiers unique by incorporating the `stamp` parameter into it's name. trait MakeUnique { fn make_unique(&mut self, stamp: usize); } -/// MakeUnique is used in generation of C headers to make DeclarationC +/// `MakeUnique` is used in generation of C headers to make `DeclarationC` /// identifiers unique. impl MakeUnique for DeclarationC { fn make_unique(&mut self, stamp: usize) { @@ -178,7 +179,7 @@ impl MakeUnique for DeclarationC { } } -/// A qucickcheck trait for describing how DeclarationC types can be +/// A qucickcheck trait for describing how `DeclarationC` types can be /// randomly generated and shrunk. impl Arbitrary for DeclarationC { fn arbitrary(g: &mut Gen) -> DeclarationC { @@ -197,20 +198,20 @@ impl Arbitrary for DeclarationC { } } -/// Enables to string and format for DeclarationC types. +/// Enables to string and format for `DeclarationC` types. impl fmt::Display for DeclarationC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - DeclarationC::FunctionPtrDecl(ref d) => write!(f, "{}", d), - DeclarationC::StructDecl(ref d) => write!(f, "{}", d), - DeclarationC::UnionDecl(ref d) => write!(f, "{}", d), - DeclarationC::VariableDecl(ref d) => write!(f, "{}", d), - DeclarationC::FunctionDecl(ref d) => write!(f, "{}", d), + DeclarationC::FunctionPtrDecl(ref d) => write!(f, "{d}"), + DeclarationC::StructDecl(ref d) => write!(f, "{d}"), + DeclarationC::UnionDecl(ref d) => write!(f, "{d}"), + DeclarationC::VariableDecl(ref d) => write!(f, "{d}"), + DeclarationC::FunctionDecl(ref d) => write!(f, "{d}"), } } } -/// A qucickcheck trait for describing how DeclarationListC types can be +/// A qucickcheck trait for describing how `DeclarationListC` types can be /// randomly generated and shrunk. impl Arbitrary for DeclarationListC { fn arbitrary(g: &mut Gen) -> DeclarationListC { @@ -220,18 +221,17 @@ impl Arbitrary for DeclarationListC { } } -/// Enables to string and format for DeclarationListC types. +/// Enables to string and format for `DeclarationListC` types. impl fmt::Display for DeclarationListC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut display = String::new(); for decl in &self.decls { - display += &format!("{}", decl); + write!(f, "{decl}")?; } - write!(f, "{}", display) + Ok(()) } } -/// A quickcheck trait for describing how BaseTypeC types can be +/// A quickcheck trait for describing how `BaseTypeC` types can be /// randomly generated and shrunk. impl Arbitrary for BaseTypeC { fn arbitrary(g: &mut Gen) -> BaseTypeC { @@ -275,14 +275,14 @@ impl Arbitrary for BaseTypeC { } } -/// Enables to string and format for BaseTypeC types, +/// Enables to string and format for `BaseTypeC` types, impl fmt::Display for BaseTypeC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.def) } } -/// A qucickcheck trait for describing how TypeQualifierC types can be +/// A qucickcheck trait for describing how `TypeQualifierC` types can be /// randomly generated and shrunk. impl Arbitrary for TypeQualifierC { fn arbitrary(g: &mut Gen) -> TypeQualifierC { @@ -293,14 +293,14 @@ impl Arbitrary for TypeQualifierC { } } -/// Enables to string and format for TypeQualifierC types. +/// Enables to string and format for `TypeQualifierC` types. impl fmt::Display for TypeQualifierC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.def) } } -/// A qucickcheck trait for describing how PointerLevelC types can be +/// A qucickcheck trait for describing how `PointerLevelC` types can be /// randomly generated and shrunk. impl Arbitrary for PointerLevelC { fn arbitrary(g: &mut Gen) -> PointerLevelC { @@ -311,14 +311,14 @@ impl Arbitrary for PointerLevelC { } } -/// Enables to string and format for PointerLevelC types. +/// Enables to string and format for `PointerLevelC` types. impl fmt::Display for PointerLevelC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.def) } } -/// A qucickcheck trait for describing how ArrayDimensionC types can be +/// A qucickcheck trait for describing how `ArrayDimensionC` types can be /// randomly generated and shrunk. impl Arbitrary for ArrayDimensionC { fn arbitrary(g: &mut Gen) -> ArrayDimensionC { @@ -330,28 +330,28 @@ impl Arbitrary for ArrayDimensionC { for _ in 1..dimensions { // 16 is an arbitrary "not too big" number for capping array size. - def += &format!("[{}]", gen_range(g, lower_bound, 16)); + let _ = write!(def, "[{}]", gen_range(g, lower_bound, 16)); } ArrayDimensionC { def } } } -/// Enables to string and format for ArrayDimensionC types. +/// Enables to string and format for `ArrayDimensionC` types. impl fmt::Display for ArrayDimensionC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.def) } } -/// MakeUnique is used in generation of C headers to make BasicTypeDeclarationC +/// `MakeUnique` is used in generation of C headers to make `BasicTypeDeclarationC` /// identifiers unique. impl MakeUnique for BasicTypeDeclarationC { fn make_unique(&mut self, stamp: usize) { - self.ident_id += &format!("_{}", stamp); + let _ = write!(self.ident_id, "_{stamp}"); } } -/// A qucickcheck trait for describing how BasicTypeDeclarationC types can be +/// A qucickcheck trait for describing how `BasicTypeDeclarationC` types can be /// randomly generated and shrunk. impl Arbitrary for BasicTypeDeclarationC { fn arbitrary(g: &mut Gen) -> BasicTypeDeclarationC { @@ -365,7 +365,7 @@ impl Arbitrary for BasicTypeDeclarationC { } } -/// Enables to string and format for BasicTypeDeclarationC types. +/// Enables to string and format for `BasicTypeDeclarationC` types. impl fmt::Display for BasicTypeDeclarationC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -380,15 +380,15 @@ impl fmt::Display for BasicTypeDeclarationC { } } -/// MakeUnique is used in generation of C headers to make StructDeclarationC +/// `MakeUnique` is used in generation of C headers to make `StructDeclarationC` /// identifiers unique. impl MakeUnique for StructDeclarationC { fn make_unique(&mut self, stamp: usize) { - self.ident_id += &format!("_{}", stamp); + let _ = write!(self.ident_id, "_{stamp}"); } } -/// A qucickcheck trait for describing how StructDeclarationC types can be +/// A qucickcheck trait for describing how `StructDeclarationC` types can be /// randomly generated and shrunk. impl Arbitrary for StructDeclarationC { fn arbitrary(g: &mut Gen) -> StructDeclarationC { @@ -417,7 +417,7 @@ impl Arbitrary for StructDeclarationC { } } -/// Enables to string and format for StructDeclarationC types. +/// Enables to string and format for `StructDeclarationC` types. impl fmt::Display for StructDeclarationC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -428,15 +428,15 @@ impl fmt::Display for StructDeclarationC { } } -/// MakeUnique is used in generation of C headers to make UnionDeclarationC +/// `MakeUnique` is used in generation of C headers to make `UnionDeclarationC` /// identifiers unique. impl MakeUnique for UnionDeclarationC { fn make_unique(&mut self, stamp: usize) { - self.ident_id += &format!("_{}", stamp); + let _ = write!(self.ident_id, "_{stamp}"); } } -/// A qucickcheck trait for describing how UnionDeclarationC types can be +/// A qucickcheck trait for describing how `UnionDeclarationC` types can be /// randomly generated and shrunk. impl Arbitrary for UnionDeclarationC { fn arbitrary(g: &mut Gen) -> UnionDeclarationC { @@ -465,7 +465,7 @@ impl Arbitrary for UnionDeclarationC { } } -/// Enables to string and format for UnionDeclarationC types. +/// Enables to string and format for `UnionDeclarationC` types. impl fmt::Display for UnionDeclarationC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -476,15 +476,15 @@ impl fmt::Display for UnionDeclarationC { } } -/// MakeUnique is used in generation of C headers to make -/// FunctionPointerDeclarationC identifiers unique. +/// `MakeUnique` is used in generation of C headers to make +/// `FunctionPointerDeclarationC` identifiers unique. impl MakeUnique for FunctionPointerDeclarationC { fn make_unique(&mut self, stamp: usize) { - self.ident_id += &format!("_{}", stamp); + let _ = write!(self.ident_id, "_{stamp}"); } } -/// A qucickcheck trait for describing how FunctionPointerDeclarationC types can +/// A qucickcheck trait for describing how `FunctionPointerDeclarationC` types can /// be randomly generated and shrunk. impl Arbitrary for FunctionPointerDeclarationC { fn arbitrary(g: &mut Gen) -> FunctionPointerDeclarationC { @@ -498,7 +498,7 @@ impl Arbitrary for FunctionPointerDeclarationC { } } -/// Enables to string and format for FunctionPointerDeclarationC types. +/// Enables to string and format for `FunctionPointerDeclarationC` types. impl fmt::Display for FunctionPointerDeclarationC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -513,15 +513,15 @@ impl fmt::Display for FunctionPointerDeclarationC { } } -/// MakeUnique is used in generation of C headers to make FunctionPrototypeC +/// `MakeUnique` is used in generation of C headers to make `FunctionPrototypeC` /// identifiers unique. impl MakeUnique for FunctionPrototypeC { fn make_unique(&mut self, stamp: usize) { - self.ident_id += &format!("_{}", stamp); + let _ = write!(self.ident_id, "_{stamp}"); } } -/// A qucickcheck trait for describing how FunctionPrototypeC types can be +/// A qucickcheck trait for describing how `FunctionPrototypeC` types can be /// randomly generated and shrunk. impl Arbitrary for FunctionPrototypeC { fn arbitrary(g: &mut Gen) -> FunctionPrototypeC { @@ -535,7 +535,7 @@ impl Arbitrary for FunctionPrototypeC { } } -/// Enables to string and format for FunctionPrototypeC types. +/// Enables to string and format for `FunctionPrototypeC` types. impl fmt::Display for FunctionPrototypeC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -550,7 +550,7 @@ impl fmt::Display for FunctionPrototypeC { } } -/// A qucickcheck trait for describing how ParameterC types can be +/// A qucickcheck trait for describing how `ParameterC` types can be /// randomly generated and shrunk. impl Arbitrary for ParameterC { fn arbitrary(g: &mut Gen) -> ParameterC { @@ -562,7 +562,7 @@ impl Arbitrary for ParameterC { } } -/// Enables to string and format for ParameterC types. +/// Enables to string and format for `ParameterC` types. impl fmt::Display for ParameterC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -573,7 +573,7 @@ impl fmt::Display for ParameterC { } } -/// A qucickcheck trait for describing how ParameterListC types can be +/// A qucickcheck trait for describing how `ParameterListC` types can be /// randomly generated and shrunk. impl Arbitrary for ParameterListC { fn arbitrary(g: &mut Gen) -> ParameterListC { @@ -583,21 +583,20 @@ impl Arbitrary for ParameterListC { } } -/// Enables to string and format for ParameterListC types. +/// Enables to string and format for `ParameterListC` types. impl fmt::Display for ParameterListC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut display = String::new(); for (i, p) in self.params.iter().enumerate() { match i { - 0 => display += &format!("{}", p), - _ => display += &format!(",{}", p), + 0 => write!(f, "{p}")?, + _ => write!(f, ",{p}")?, } } - write!(f, "{}", display) + Ok(()) } } -/// A qucickcheck trait for describing how HeaderC types can be +/// A qucickcheck trait for describing how `HeaderC` types can be /// randomly generated and shrunk. impl Arbitrary for HeaderC { fn arbitrary(g: &mut Gen) -> HeaderC { @@ -609,14 +608,13 @@ impl Arbitrary for HeaderC { } } -/// Enables to string and format for HeaderC types. +/// Enables to string and format for `HeaderC` types. impl fmt::Display for HeaderC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut display = String::new(); for decl in &self.def.decls { - display += &format!("{}", decl); + write!(f, "{decl}")?; } - write!(f, "{}", display) + Ok(()) } } @@ -624,7 +622,7 @@ impl fmt::Display for HeaderC { /// generated C code rather than the data structures that contain it. impl fmt::Debug for HeaderC { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } diff --git a/bindgen-tests/tests/quickchecking/src/lib.rs b/bindgen-tests/tests/quickchecking/src/lib.rs index 631c1c679e..7567a3bea6 100644 --- a/bindgen-tests/tests/quickchecking/src/lib.rs +++ b/bindgen-tests/tests/quickchecking/src/lib.rs @@ -3,25 +3,15 @@ //! ## Example //! //! ```rust -//! extern crate quickcheck; -//! extern crate quickchecking; //! use quickcheck::{Arbitrary, Gen}; //! use quickchecking::fuzzers; //! -//! fn main() { -//! let generate_range: usize = 10; // Determines things like the length of -//! // arbitrary vectors generated. -//! let header = fuzzers::HeaderC::arbitrary( -//! &mut Gen::new(generate_range)); -//! println!("{}", header); -//! } +//! let generate_range: usize = 10; // Determines things like the length of +//! // arbitrary vectors generated. +//! let header = fuzzers::HeaderC::arbitrary(&mut Gen::new(generate_range)); +//! println!("{header}"); //! ``` -//! #![deny(missing_docs)] -#[macro_use] -extern crate lazy_static; -extern crate quickcheck; -extern crate tempfile; use quickcheck::{Gen, QuickCheck, TestResult}; use std::error::Error; @@ -42,15 +32,12 @@ struct Context { } // Initialize global context. -lazy_static! { - static ref CONTEXT: Mutex = - Mutex::new(Context { output_path: None }); -} +static CONTEXT: Mutex = Mutex::new(Context { output_path: None }); // Passes fuzzed header to the `csmith-fuzzing/predicate.py` script, returns // output of the associated command. fn run_predicate_script( - header: fuzzers::HeaderC, + header: &fuzzers::HeaderC, ) -> Result> { let dir = Builder::new().prefix("bindgen_prop").tempdir()?; let header_path = dir.path().join("prop_test.h"); @@ -90,11 +77,12 @@ fn run_predicate_script( // Generatable property. Pass generated headers off to run through the // `csmith-fuzzing/predicate.py` script. Success is measured by the success // status of that command. +#[allow(clippy::needless_pass_by_value)] fn bindgen_prop(header: fuzzers::HeaderC) -> TestResult { - match run_predicate_script(header) { + match run_predicate_script(&header) { Ok(o) => TestResult::from_bool(o.status.success()), Err(e) => { - println!("{:?}", e); + println!("{e:?}"); TestResult::from_bool(false) } } @@ -116,5 +104,5 @@ pub fn test_bindgen( QuickCheck::new() .tests(tests) .gen(Gen::new(generate_range)) - .quickcheck(bindgen_prop as fn(fuzzers::HeaderC) -> TestResult) + .quickcheck(bindgen_prop as fn(fuzzers::HeaderC) -> TestResult); } diff --git a/bindgen-tests/tests/quickchecking/tests/fuzzed-c-headers.rs b/bindgen-tests/tests/quickchecking/tests/fuzzed-c-headers.rs index e394efe387..0735a70c47 100644 --- a/bindgen-tests/tests/quickchecking/tests/fuzzed-c-headers.rs +++ b/bindgen-tests/tests/quickchecking/tests/fuzzed-c-headers.rs @@ -1,6 +1,3 @@ -extern crate quickcheck; -extern crate quickchecking; - use quickcheck::{Arbitrary, Gen}; use quickchecking::fuzzers::{ ArrayDimensionC, BaseTypeC, BasicTypeDeclarationC, DeclarationC, diff --git a/bindgen-tests/tests/stylo_sanity.rs b/bindgen-tests/tests/stylo_sanity.rs index e9ec69bcb8..7b94e2989e 100755 --- a/bindgen-tests/tests/stylo_sanity.rs +++ b/bindgen-tests/tests/stylo_sanity.rs @@ -1,7 +1,3 @@ -// Don't want to copy that nasty `cfg` below... -#[allow(unused_extern_crates)] -extern crate bindgen; - /// A sanity test that we can generate bindings for Stylo. /// /// We don't assert on expected output because its just too big. The output will diff --git a/bindgen-tests/tests/tests.rs b/bindgen-tests/tests/tests.rs index c096b2e81e..3cc7cbe415 100644 --- a/bindgen-tests/tests/tests.rs +++ b/bindgen-tests/tests/tests.rs @@ -1,9 +1,3 @@ -extern crate bindgen; -extern crate clap; -#[cfg(feature = "logging")] -extern crate env_logger; -extern crate shlex; - use bindgen::{clang_version, Builder}; use owo_colors::{OwoColorize, Style}; use similar::{ChangeTag, TextDiff}; @@ -13,10 +7,7 @@ use std::fs; use std::io::{BufRead, BufReader, Error, ErrorKind, Read, Write}; use std::path::{Path, PathBuf}; -use crate::options::builder_from_flags; - -#[path = "../../bindgen-cli/options.rs"] -mod options; +use bindgen::builder_from_flags; mod parse_callbacks; @@ -35,9 +26,10 @@ fn should_overwrite_expected() -> bool { if var == "1" { return true; } - if var != "0" && var != "" { - panic!("Invalid value of BINDGEN_OVERWRITE_EXPECTED"); - } + assert!( + var == "0" || var.is_empty(), + "Invalid value of BINDGEN_OVERWRITE_EXPECTED" + ); } false } @@ -49,9 +41,9 @@ fn error_diff_mismatch( filename: &Path, ) -> Result<(), Error> { println!("diff expected generated"); - println!("--- expected: {:?}", filename); + println!("--- expected: {filename:?}"); if let Some(header) = header { - println!("+++ generated from: {:?}", header); + println!("+++ generated from: {header:?}"); } show_diff(expected, actual); @@ -64,9 +56,10 @@ fn error_diff_mismatch( if let Some(var) = env::var_os("BINDGEN_TESTS_DIFFTOOL") { //usecase: var = "meld" -> You can hand check differences - let name = match filename.components().last() { - Some(std::path::Component::Normal(name)) => name, - _ => panic!("Why is the header variable so weird?"), + let Some(std::path::Component::Normal(name)) = + filename.components().next_back() + else { + panic!("Why is the header variable so weird?") }; let actual_result_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join(name); @@ -162,9 +155,9 @@ fn compare_generated_header( } else if maj >= 9 { "9".to_owned() } else { - format!("{}.{}", maj, min) + format!("{maj}.{min}") }; - expectation.push(format!("libclang-{}", version_str)); + expectation.push(format!("libclang-{version_str}")); } } } @@ -194,7 +187,7 @@ fn compare_generated_header( header.display(), looked_at, ), - }; + } let (builder, roundtrip_builder) = builder.into_builder(check_roundtrip)?; @@ -203,7 +196,7 @@ fn compare_generated_header( Ok(bindings) => format_code(bindings.to_string()).map_err(|err| { Error::new( ErrorKind::Other, - format!("Cannot parse the generated bindings: {}", err), + format!("Cannot parse the generated bindings: {err}"), ) })?, Err(_) => "/* error generating bindings */\n".into(), @@ -228,7 +221,7 @@ fn compare_generated_header( if let Err(e) = compare_generated_header(header, roundtrip_builder, false) { - return Err(Error::new(ErrorKind::Other, format!("Checking CLI flags roundtrip errored! You probably need to fix Builder::command_line_flags. {}", e))); + return Err(Error::new(ErrorKind::Other, format!("Checking CLI flags roundtrip errored! You probably need to fix Builder::command_line_flags. {e}"))); } } @@ -368,7 +361,7 @@ macro_rules! test_header { }); if let Err(err) = result { - panic!("{}", err); + panic!("{err}"); } } }; @@ -380,7 +373,7 @@ include!(concat!(env!("OUT_DIR"), "/tests.rs")); #[test] #[cfg_attr(target_os = "windows", ignore)] fn test_clang_env_args() { - std::env::set_var( + env::set_var( "BINDGEN_EXTRA_CLANG_ARGS", "-D_ENV_ONE=1 -D_ENV_TWO=\"2 -DNOT_THREE=1\"", ); @@ -399,10 +392,10 @@ fn test_clang_env_args() { let actual = format_code(actual).unwrap(); let expected = format_code( - "extern \"C\" { + "unsafe extern \"C\" { pub static x: [::std::os::raw::c_int; 1usize]; } -extern \"C\" { +unsafe extern \"C\" { pub static y: [::std::os::raw::c_int; 1usize]; } ", @@ -425,7 +418,7 @@ fn test_header_contents() { let actual = format_code(actual).unwrap(); let expected = format_code( - "extern \"C\" { + "unsafe extern \"C\" { pub fn foo(a: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; } ", @@ -521,10 +514,10 @@ fn test_multiple_header_contents() { let actual = format_code(actual).unwrap(); let expected = format_code( - "extern \"C\" { + "unsafe extern \"C\" { pub fn foo2(b: *const ::std::os::raw::c_char) -> f32; } -extern \"C\" { +unsafe extern \"C\" { pub fn foo(a: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; } ", @@ -571,6 +564,60 @@ fn test_mixed_header_and_header_contents() { } } +#[test] +fn test_macro_fallback_non_system_dir() { + let actual = builder() + .header(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/macro_fallback_test_headers/one_header.h" + )) + .header(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/macro_fallback_test_headers/another_header.h" + )) + .clang_macro_fallback() + .clang_arg(format!("-I{}/tests/headers", env!("CARGO_MANIFEST_DIR"))) + .generate() + .unwrap() + .to_string(); + + let actual = format_code(actual).unwrap(); + + let (expected_filename, expected) = if let Some((9, _)) = + clang_version().parsed + { + let expected_filename = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/expectations/tests/libclang-9/macro_fallback_non_system_dir.rs", + ); + let expected = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/expectations/tests/libclang-9/macro_fallback_non_system_dir.rs", + )); + (expected_filename, expected) + } else { + let expected_filename = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/expectations/tests/test_macro_fallback_non_system_dir.rs", + ); + let expected = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/expectations/tests/test_macro_fallback_non_system_dir.rs", + )); + (expected_filename, expected) + }; + let expected = format_code(expected).unwrap(); + if expected != actual { + error_diff_mismatch( + &actual, + &expected, + None, + Path::new(expected_filename), + ) + .unwrap(); + } +} + #[test] // Doesn't support executing sh file on Windows. // We may want to implement it in Rust so that we support all systems. @@ -607,8 +654,8 @@ fn emit_depfile() { builder.into_builder(check_roundtrip).unwrap(); let _bindings = builder.generate().unwrap(); - let observed = std::fs::read_to_string(observed_depfile).unwrap(); - let expected = std::fs::read_to_string(expected_depfile).unwrap(); + let observed = fs::read_to_string(observed_depfile).unwrap(); + let expected = fs::read_to_string(expected_depfile).unwrap(); assert_eq!(observed.trim(), expected.trim()); } @@ -648,7 +695,7 @@ fn dump_preprocessed_input() { ); } -fn build_flags_output_helper(builder: &bindgen::Builder) { +fn build_flags_output_helper(builder: &Builder) { let mut command_line_flags = builder.command_line_flags(); command_line_flags.insert(0, "bindgen".to_string()); @@ -657,17 +704,16 @@ fn build_flags_output_helper(builder: &bindgen::Builder) { .map(|x| format!("{}", shlex::try_quote(x).unwrap())) .collect(); let flags_str = flags_quoted.join(" "); - println!("{}", flags_str); + println!("{flags_str}"); let (builder, _output, _verbose) = - crate::options::builder_from_flags(command_line_flags.into_iter()) - .unwrap(); + builder_from_flags(command_line_flags.into_iter()).unwrap(); builder.generate().expect("failed to generate bindings"); } #[test] fn commandline_multiple_headers() { - let bindings = bindgen::Builder::default() + let bindings = Builder::default() .header("tests/headers/char.h") .header("tests/headers/func_ptr.h") .header("tests/headers/16-byte-alignment.h"); diff --git a/bindgen/Cargo.toml b/bindgen/Cargo.toml index 95293daf61..c01f8f0c44 100644 --- a/bindgen/Cargo.toml +++ b/bindgen/Cargo.toml @@ -1,9 +1,11 @@ +lints.workspace = true + [package] authors = [ - "Jyun-Yan You ", - "Emilio Cobos Álvarez ", - "Nick Fitzgerald ", - "The Servo project developers", + "Jyun-Yan You ", + "Emilio Cobos Álvarez ", + "Nick Fitzgerald ", + "The Servo project developers", ] description = "Automatically generates Rust FFI bindings to C and C++ libraries." keywords = ["bindings", "ffi", "code-generation"] @@ -14,47 +16,45 @@ readme = "../README.md" repository = "https://github.com/rust-lang/rust-bindgen" documentation = "https://docs.rs/bindgen" homepage = "https://rust-lang.github.io/rust-bindgen/" -version = "0.69.4" -edition = "2018" +version = "0.71.1" build = "build.rs" -# If you change this, also update README.md and msrv in .github/workflows/bindgen.yml -rust-version = "1.60.0" +rust-version.workspace = true +edition.workspace = true [lib] name = "bindgen" path = "lib.rs" [dependencies] -annotate-snippets = { version = "0.9.1", features = ["color"], optional = true } -bitflags = "2.2.1" -cexpr = "0.6" -clang-sys = { version = "1", features = ["clang_6_0"] } -itertools = { version = ">=0.10,<0.13", default-features = false } -lazy_static = "1" -lazycell = "1" -log = { version = "0.4", optional = true } -prettyplease = { version = "0.2.7", optional = true, features = ["verbatim"] } -proc-macro2 = { version = "1", default-features = false } -quote = { version = "1", default-features = false } -regex = { version = "1.5.3", default-features = false, features = ["std", "unicode-perl"] } -rustc-hash = "1.0.1" -shlex = "1" -syn = { version = "2.0", features = ["full", "extra-traits", "visit-mut"] } -which = { version = "4.2.1", optional = true, default-features = false } +annotate-snippets = { workspace = true, optional = true } +bitflags.workspace = true +cexpr.workspace = true +clang-sys = { workspace = true, features = ["clang_11_0"] } +clap = { workspace = true, features = ["derive"], optional = true } +clap_complete = { workspace = true, optional = true } +itertools = { workspace = true } +log = { workspace = true, optional = true } +prettyplease = { workspace = true, optional = true, features = ["verbatim"] } +proc-macro2.workspace = true +quote.workspace = true +regex = { workspace = true, features = ["std", "unicode-perl"] } +rustc-hash.workspace = true +shlex.workspace = true +syn = { workspace = true, features = ["full", "extra-traits", "visit-mut"] } [features] -default = ["logging", "prettyplease", "runtime", "which-rustfmt"] +default = ["logging", "prettyplease", "runtime"] logging = ["dep:log"] static = ["clang-sys/static"] runtime = ["clang-sys/runtime"] -# Dynamically discover a `rustfmt` binary using the `which` crate -which-rustfmt = ["dep:which"] +# This feature is no longer used for anything and should be removed in bindgen 0.70 +which-rustfmt = [] experimental = ["dep:annotate-snippets"] ## The following features are for internal use and they shouldn't be used if ## you're not hacking on bindgen # Features used by `bindgen-cli` -__cli = [] +__cli = ["dep:clap", "dep:clap_complete"] # Features used for CI testing __testing_only_extra_assertions = [] __testing_only_libclang_9 = [] diff --git a/bindgen/build.rs b/bindgen/build.rs index 8407ceae8f..4fb2d3075e 100644 --- a/bindgen/build.rs +++ b/bindgen/build.rs @@ -20,10 +20,10 @@ fn main() { println!("cargo:rerun-if-env-changed=BINDGEN_EXTRA_CLANG_ARGS"); println!( "cargo:rerun-if-env-changed=BINDGEN_EXTRA_CLANG_ARGS_{}", - std::env::var("TARGET").unwrap() + env::var("TARGET").unwrap() ); println!( "cargo:rerun-if-env-changed=BINDGEN_EXTRA_CLANG_ARGS_{}", - std::env::var("TARGET").unwrap().replace('-', "_") + env::var("TARGET").unwrap().replace('-', "_") ); } diff --git a/bindgen/callbacks.rs b/bindgen/callbacks.rs index c22ba975dd..cd7bb9773d 100644 --- a/bindgen/callbacks.rs +++ b/bindgen/callbacks.rs @@ -7,21 +7,16 @@ pub use crate::ir::int::IntKind; use std::fmt; /// An enum to allow ignoring parsing of macros. -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] pub enum MacroParsingBehavior { /// Ignore the macro, generating no code for it, or anything that depends on /// it. Ignore, /// The default behavior bindgen would have otherwise. + #[default] Default, } -impl Default for MacroParsingBehavior { - fn default() -> Self { - MacroParsingBehavior::Default - } -} - /// A trait to allow configuring different kinds of types in different /// situations. pub trait ParseCallbacks: fmt::Debug { @@ -134,6 +129,14 @@ pub trait ParseCallbacks: fmt::Debug { vec![] } + /// Provide a list of custom attributes. + /// + /// If no additional attributes are wanted, this function should return an + /// empty `Vec`. + fn add_attributes(&self, _info: &AttributeInfo<'_>) -> Vec { + vec![] + } + /// Process a source code comment. fn process_comment(&self, _comment: &str) -> Option { None @@ -159,6 +162,83 @@ pub trait ParseCallbacks: fmt::Debug { fn wrap_as_variadic_fn(&self, _name: &str) -> Option { None } + + /// This will get called everytime an item (currently struct, union, and alias) is found with some information about it + fn new_item_found(&self, _id: DiscoveredItemId, _item: DiscoveredItem) {} + + // TODO add callback for ResolvedTypeRef +} + +/// An identifier for a discovered item. Used to identify an aliased type (see [`DiscoveredItem::Alias`]) +#[derive(Ord, PartialOrd, PartialEq, Eq, Hash, Debug, Clone, Copy)] +pub struct DiscoveredItemId(usize); + +impl DiscoveredItemId { + /// Constructor + pub fn new(value: usize) -> Self { + Self(value) + } +} + +/// Struct passed to [`ParseCallbacks::new_item_found`] containing information about discovered +/// items (struct, union, and alias) +#[derive(Debug, Hash, Clone, Ord, PartialOrd, Eq, PartialEq)] +pub enum DiscoveredItem { + /// Represents a struct with its original name in C and its generated binding name + Struct { + /// The original name (learnt from C) of the structure + /// Can be None if the union is anonymous. + original_name: Option, + + /// The name of the generated binding + final_name: String, + }, + + /// Represents a union with its original name in C and its generated binding name + Union { + /// The original name (learnt from C) of the structure. + /// Can be None if the union is anonymous. + original_name: Option, + + /// The name of the generated binding + final_name: String, + }, + + /// Represents an alias like a typedef + /// ```c + /// typedef struct MyStruct { + /// ... + /// } StructAlias; + /// ``` + /// Here, the name of the alias is `StructAlias` and it's an alias for `MyStruct` + Alias { + /// The name of the alias in C (`StructAlias`) + alias_name: String, + + /// The identifier of the discovered type + alias_for: DiscoveredItemId, + }, + + /// Represents an enum. + Enum { + /// The final name of the generated binding + final_name: String, + }, + + /// A function or method. + Function { + /// The final name used. + final_name: String, + }, + + /// A method. + Method { + /// The final name used. + final_name: String, + + /// Type to which this method belongs. + parent: DiscoveredItemId, + }, // modules, etc. } /// Relevant information about a type to which new derive attributes will be added using @@ -172,6 +252,17 @@ pub struct DeriveInfo<'a> { pub kind: TypeKind, } +/// Relevant information about a type to which new attributes will be added using +/// [`ParseCallbacks::add_attributes`]. +#[derive(Debug)] +#[non_exhaustive] +pub struct AttributeInfo<'a> { + /// The name of the type. + pub name: &'a str, + /// The kind of the type. + pub kind: TypeKind, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// The kind of the current type. pub enum TypeKind { @@ -192,7 +283,7 @@ pub struct ItemInfo<'a> { pub kind: ItemKind, } -/// An enum indicating the kind of item for an ItemInfo. +/// An enum indicating the kind of item for an `ItemInfo`. #[non_exhaustive] pub enum ItemKind { /// A Function @@ -210,4 +301,6 @@ pub struct FieldInfo<'a> { pub type_name: &'a str, /// The name of the field. pub field_name: &'a str, + /// The name of the type of the field. + pub field_type_name: Option<&'a str>, } diff --git a/bindgen/clang.rs b/bindgen/clang.rs index a9a0ec814f..04fe3e1538 100644 --- a/bindgen/clang.rs +++ b/bindgen/clang.rs @@ -10,9 +10,11 @@ use std::cmp; use std::ffi::{CStr, CString}; use std::fmt; +use std::fs::OpenOptions; use std::hash::Hash; use std::hash::Hasher; use std::os::raw::{c_char, c_int, c_longlong, c_uint, c_ulong, c_ulonglong}; +use std::sync::OnceLock; use std::{mem, ptr, slice}; /// Type representing a clang attribute. @@ -214,10 +216,10 @@ impl Cursor { }) .or_else(|| { let canonical = self.canonical(); - if canonical != *self { - canonical.num_template_args() - } else { + if canonical == *self { None + } else { + canonical.num_template_args() } }) } @@ -492,7 +494,7 @@ impl Cursor { where Visitor: FnMut(Cursor) -> CXChildVisitResult, { - let data = &mut visitor as *mut Visitor; + let data = ptr::addr_of_mut!(visitor); unsafe { clang_visitChildren(self.x, visit_children::, data.cast()); } @@ -786,7 +788,7 @@ impl Cursor { let found_attr = &mut found_attrs[idx]; if !*found_attr { // `attr.name` and` attr.token_kind` are checked against unexposed attributes only. - if attr.kind.map_or(false, |k| k == kind) || + if attr.kind == Some(kind) || (kind == CXCursor_UnexposedAttr && cur.tokens().iter().any(|t| { t.kind == attr.token_kind && @@ -874,9 +876,9 @@ impl Cursor { unsafe { clang_getCXXAccessSpecifier(self.x) } } - /// Is the cursor's referent publically accessible in C++? + /// Is the cursor's referent publicly accessible in C++? /// - /// Returns true if self.access_specifier() is `CX_CXXPublic` or + /// Returns true if `self.access_specifier()` is `CX_CXXPublic` or /// `CX_CXXInvalidAccessSpecifier`. pub(crate) fn public_accessible(&self) -> bool { let access = self.access_specifier(); @@ -955,19 +957,22 @@ impl Cursor { .collect() } - /// Obtain the real path name of a cursor of InclusionDirective kind. + /// Obtain the real path name of a cursor of `InclusionDirective` kind. /// /// Returns None if the cursor does not include a file, otherwise the file's full name pub(crate) fn get_included_file_name(&self) -> Option { - let file = unsafe { clang_sys::clang_getIncludedFile(self.x) }; + let file = unsafe { clang_getIncludedFile(self.x) }; if file.is_null() { None } else { - Some(unsafe { - cxstring_into_string(clang_sys::clang_getFileName(file)) - }) + Some(unsafe { cxstring_into_string(clang_getFileName(file)) }) } } + + /// Is this cursor's referent a namespace that is inline? + pub(crate) fn is_inline_namespace(&self) -> bool { + unsafe { clang_Cursor_isInlineNamespace(self.x) != 0 } + } } /// A struct that owns the tokenizer result from a given cursor. @@ -1009,7 +1014,7 @@ impl<'a> RawTokens<'a> { } } -impl<'a> Drop for RawTokens<'a> { +impl Drop for RawTokens<'_> { fn drop(&mut self) { if !self.tokens.is_null() { unsafe { @@ -1040,13 +1045,11 @@ pub(crate) struct ClangToken { impl ClangToken { /// Get the token spelling, without being converted to utf-8. pub(crate) fn spelling(&self) -> &[u8] { - let c_str = unsafe { - CStr::from_ptr(clang_getCString(self.spelling) as *const _) - }; + let c_str = unsafe { CStr::from_ptr(clang_getCString(self.spelling)) }; c_str.to_bytes() } - /// Converts a ClangToken to a `cexpr` token if possible. + /// Converts a `ClangToken` to a `cexpr` token if possible. pub(crate) fn as_cexpr_token(&self) -> Option { use cexpr::token; @@ -1059,7 +1062,7 @@ impl ClangToken { // expressions, so we strip them down here. CXToken_Comment => return None, _ => { - warn!("Found unexpected token kind: {:?}", self); + warn!("Found unexpected token kind: {self:?}"); return None; } }; @@ -1083,7 +1086,7 @@ pub(crate) struct ClangTokenIterator<'a> { raw: slice::Iter<'a, CXToken>, } -impl<'a> Iterator for ClangTokenIterator<'a> { +impl Iterator for ClangTokenIterator<'_> { type Item = ClangToken; fn next(&mut self) -> Option { @@ -1093,9 +1096,9 @@ impl<'a> Iterator for ClangTokenIterator<'a> { let spelling = clang_getTokenSpelling(self.tu, *raw); let extent = clang_getTokenExtent(self.tu, *raw); Some(ClangToken { - kind, - extent, spelling, + extent, + kind, }) } } @@ -1105,10 +1108,8 @@ impl<'a> Iterator for ClangTokenIterator<'a> { /// (including '_') and does not start with a digit. pub(crate) fn is_valid_identifier(name: &str) -> bool { let mut chars = name.chars(); - let first_valid = chars - .next() - .map(|c| c.is_alphabetic() || c == '_') - .unwrap_or(false); + let first_valid = + chars.next().is_some_and(|c| c.is_alphabetic() || c == '_'); first_valid && chars.all(|c| c.is_alphanumeric() || c == '_') } @@ -1121,7 +1122,7 @@ extern "C" fn visit_children( where Visitor: FnMut(Cursor) -> CXChildVisitResult, { - let func: &mut Visitor = unsafe { &mut *(data as *mut Visitor) }; + let func: &mut Visitor = unsafe { &mut *data.cast::() }; let child = Cursor { x: cur }; (*func)(child) @@ -1137,7 +1138,7 @@ impl Eq for Cursor {} impl Hash for Cursor { fn hash(&self, state: &mut H) { - unsafe { clang_hashCursor(self.x) }.hash(state) + unsafe { clang_hashCursor(self.x) }.hash(state); } } @@ -1440,10 +1441,10 @@ impl Type { /// elements. pub(crate) fn num_elements(&self) -> Option { let num_elements_returned = unsafe { clang_getNumElements(self.x) }; - if num_elements_returned != -1 { - Some(num_elements_returned as usize) - } else { + if num_elements_returned == -1 { None + } else { + Some(num_elements_returned as usize) } } @@ -1491,6 +1492,15 @@ impl Type { } } + /// For atomic types, get the underlying type. + pub(crate) fn atomic_value_type(&self) -> Type { + unsafe { + Type { + x: clang_Type_getValueType(self.x), + } + } + } + /// Is this a valid type? pub(crate) fn is_valid(&self) -> bool { self.kind() != CXType_Invalid @@ -1506,7 +1516,7 @@ impl Type { // Yep, the spelling of this containing type-parameter is extremely // nasty... But can happen in . Unfortunately I couldn't // reduce it enough :( - self.template_args().map_or(false, |args| args.len() > 0) && + self.template_args().is_some_and(|args| args.len() > 0) && !matches!( self.declaration().kind(), CXCursor_ClassTemplatePartialSpecialization | @@ -1527,13 +1537,13 @@ impl Type { pub(crate) fn is_associated_type(&self) -> bool { // This is terrible :( fn hacky_parse_associated_type>(spelling: S) -> bool { - lazy_static! { - static ref ASSOC_TYPE_RE: regex::Regex = regex::Regex::new( - r"typename type\-parameter\-\d+\-\d+::.+" - ) - .unwrap(); - } - ASSOC_TYPE_RE.is_match(spelling.as_ref()) + static ASSOC_TYPE_RE: OnceLock = OnceLock::new(); + ASSOC_TYPE_RE + .get_or_init(|| { + regex::Regex::new(r"typename type\-parameter\-\d+\-\d+::.+") + .unwrap() + }) + .is_match(spelling.as_ref()) } self.kind() == CXType_Unexposed && @@ -1608,7 +1618,7 @@ impl SourceLocation { let mut line = 0; let mut col = 0; let mut off = 0; - clang_getSpellingLocation( + clang_getFileLocation( self.x, &mut file, &mut line, &mut col, &mut off, ); (File { x: file }, line as usize, col as usize, off as usize) @@ -1620,7 +1630,7 @@ impl fmt::Display for SourceLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (file, line, col, _) = self.location(); if let Some(name) = file.name() { - write!(f, "{}:{}:{}", name, line, col) + write!(f, "{name}:{line}:{col}") } else { "builtin definitions".fmt(f) } @@ -1629,7 +1639,7 @@ impl fmt::Display for SourceLocation { impl fmt::Debug for SourceLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } @@ -1749,9 +1759,9 @@ impl File { fn cxstring_to_string_leaky(s: CXString) -> String { if s.data.is_null() { - return "".to_owned(); + return String::new(); } - let c_str = unsafe { CStr::from_ptr(clang_getCString(s) as *const _) }; + let c_str = unsafe { CStr::from_ptr(clang_getCString(s)) }; c_str.to_string_lossy().into_owned() } @@ -1777,7 +1787,7 @@ impl Index { pub(crate) fn new(pch: bool, diag: bool) -> Index { unsafe { Index { - x: clang_createIndex(pch as c_int, diag as c_int), + x: clang_createIndex(c_int::from(pch), c_int::from(diag)), } } } @@ -1868,6 +1878,25 @@ impl TranslationUnit { } } + /// Save a translation unit to the given file. + pub(crate) fn save(&mut self, file: &str) -> Result<(), CXSaveError> { + let Ok(file) = CString::new(file) else { + return Err(CXSaveError_Unknown); + }; + let ret = unsafe { + clang_saveTranslationUnit( + self.x, + file.as_ptr(), + clang_defaultSaveOptions(self.x), + ) + }; + if ret != 0 { + Err(ret) + } else { + Ok(()) + } + } + /// Is this the null translation unit? pub(crate) fn is_null(&self) -> bool { self.x.is_null() @@ -1882,6 +1911,87 @@ impl Drop for TranslationUnit { } } +/// Translation unit used for macro fallback parsing +pub(crate) struct FallbackTranslationUnit { + file_path: String, + pch_path: String, + idx: Box, + tu: TranslationUnit, +} + +impl fmt::Debug for FallbackTranslationUnit { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "FallbackTranslationUnit {{ }}") + } +} + +impl FallbackTranslationUnit { + /// Create a new fallback translation unit + pub(crate) fn new( + file: String, + pch_path: String, + c_args: &[Box], + ) -> Option { + // Create empty file + OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(&file) + .ok()?; + + let f_index = Box::new(Index::new(true, false)); + let f_translation_unit = TranslationUnit::parse( + &f_index, + &file, + c_args, + &[], + CXTranslationUnit_None, + )?; + Some(FallbackTranslationUnit { + file_path: file, + pch_path, + tu: f_translation_unit, + idx: f_index, + }) + } + + /// Get reference to underlying translation unit. + pub(crate) fn translation_unit(&self) -> &TranslationUnit { + &self.tu + } + + /// Reparse a translation unit. + pub(crate) fn reparse( + &mut self, + unsaved_contents: &str, + ) -> Result<(), CXErrorCode> { + let unsaved = &[UnsavedFile::new(&self.file_path, unsaved_contents)]; + let mut c_unsaved: Vec = + unsaved.iter().map(|f| f.x).collect(); + let ret = unsafe { + clang_reparseTranslationUnit( + self.tu.x, + unsaved.len() as c_uint, + c_unsaved.as_mut_ptr(), + clang_defaultReparseOptions(self.tu.x), + ) + }; + if ret != 0 { + Err(ret) + } else { + Ok(()) + } + } +} + +impl Drop for FallbackTranslationUnit { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.file_path); + let _ = std::fs::remove_file(&self.pch_path); + } +} + /// A diagnostic message generated while parsing a translation unit. pub(crate) struct Diagnostic { x: CXDiagnostic, @@ -1968,26 +2078,25 @@ pub(crate) fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { let prefix = prefix.as_ref(); print_indent( depth, - format!(" {}kind = {}", prefix, kind_to_str(c.kind())), + format!(" {prefix}kind = {}", kind_to_str(c.kind())), ); print_indent( depth, - format!(" {}spelling = \"{}\"", prefix, c.spelling()), + format!(" {prefix}spelling = \"{}\"", c.spelling()), ); - print_indent(depth, format!(" {}location = {}", prefix, c.location())); + print_indent(depth, format!(" {prefix}location = {}", c.location())); print_indent( depth, - format!(" {}is-definition? {}", prefix, c.is_definition()), + format!(" {prefix}is-definition? {}", c.is_definition()), ); print_indent( depth, - format!(" {}is-declaration? {}", prefix, c.is_declaration()), + format!(" {prefix}is-declaration? {}", c.is_declaration()), ); print_indent( depth, format!( - " {}is-inlined-function? {}", - prefix, + " {prefix}is-inlined-function? {}", c.is_inlined_function() ), ); @@ -1996,23 +2105,19 @@ pub(crate) fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { if templ_kind != CXCursor_NoDeclFound { print_indent( depth, - format!( - " {}template-kind = {}", - prefix, - kind_to_str(templ_kind) - ), + format!(" {prefix}template-kind = {}", kind_to_str(templ_kind)), ); } if let Some(usr) = c.usr() { - print_indent(depth, format!(" {}usr = \"{}\"", prefix, usr)); + print_indent(depth, format!(" {prefix}usr = \"{usr}\"")); } if let Ok(num) = c.num_args() { - print_indent(depth, format!(" {}number-of-args = {}", prefix, num)); + print_indent(depth, format!(" {prefix}number-of-args = {num}")); } if let Some(num) = c.num_template_args() { print_indent( depth, - format!(" {}number-of-template-args = {}", prefix, num), + format!(" {prefix}number-of-template-args = {num}"), ); } @@ -2021,28 +2126,28 @@ pub(crate) fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { Some(w) => w.to_string(), None => "".to_string(), }; - print_indent(depth, format!(" {}bit-width = {}", prefix, width)); + print_indent(depth, format!(" {prefix}bit-width = {width}")); } if let Some(ty) = c.enum_type() { print_indent( depth, - format!(" {}enum-type = {}", prefix, type_to_str(ty.kind())), + format!(" {prefix}enum-type = {}", type_to_str(ty.kind())), ); } if let Some(val) = c.enum_val_signed() { - print_indent(depth, format!(" {}enum-val = {}", prefix, val)); + print_indent(depth, format!(" {prefix}enum-val = {val}")); } if let Some(ty) = c.typedef_type() { print_indent( depth, - format!(" {}typedef-type = {}", prefix, type_to_str(ty.kind())), + format!(" {prefix}typedef-type = {}", type_to_str(ty.kind())), ); } if let Some(ty) = c.ret_type() { print_indent( depth, - format!(" {}ret-type = {}", prefix, type_to_str(ty.kind())), + format!(" {prefix}ret-type = {}", type_to_str(ty.kind())), ); } @@ -2092,16 +2197,16 @@ pub(crate) fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { let prefix = prefix.as_ref(); let kind = ty.kind(); - print_indent(depth, format!(" {}kind = {}", prefix, type_to_str(kind))); + print_indent(depth, format!(" {prefix}kind = {}", type_to_str(kind))); if kind == CXType_Invalid { return; } - print_indent(depth, format!(" {}cconv = {}", prefix, ty.call_conv())); + print_indent(depth, format!(" {prefix}cconv = {}", ty.call_conv())); print_indent( depth, - format!(" {}spelling = \"{}\"", prefix, ty.spelling()), + format!(" {prefix}spelling = \"{}\"", ty.spelling()), ); let num_template_args = unsafe { clang_Type_getNumTemplateArguments(ty.x) }; @@ -2109,20 +2214,16 @@ pub(crate) fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { print_indent( depth, format!( - " {}number-of-template-args = {}", - prefix, num_template_args + " {prefix}number-of-template-args = {num_template_args}" ), ); } if let Some(num) = ty.num_elements() { - print_indent( - depth, - format!(" {}number-of-elements = {}", prefix, num), - ); + print_indent(depth, format!(" {prefix}number-of-elements = {num}")); } print_indent( depth, - format!(" {}is-variadic? {}", prefix, ty.is_variadic()), + format!(" {prefix}is-variadic? {}", ty.is_variadic()), ); let canonical = ty.canonical_type(); @@ -2250,7 +2351,7 @@ impl EvalResult { if unsafe { clang_EvalResult_isUnsignedInt(self.x) } != 0 { let value = unsafe { clang_EvalResult_getAsUnsigned(self.x) }; - if value > i64::max_value() as c_ulonglong { + if value > i64::MAX as c_ulonglong { return None; } @@ -2258,10 +2359,10 @@ impl EvalResult { } let value = unsafe { clang_EvalResult_getAsLongLong(self.x) }; - if value > i64::max_value() as c_longlong { + if value > i64::MAX as c_longlong { return None; } - if value < i64::min_value() as c_longlong { + if value < i64::MIN as c_longlong { return None; } #[allow(clippy::unnecessary_cast)] diff --git a/bindgen/codegen/bitfield_unit.rs b/bindgen/codegen/bitfield_unit.rs index 73ec2bd629..59c66f8cb7 100644 --- a/bindgen/codegen/bitfield_unit.rs +++ b/bindgen/codegen/bitfield_unit.rs @@ -16,12 +16,7 @@ where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub fn get_bit(&self, index: usize) -> bool { - debug_assert!(index / 8 < self.storage.as_ref().len()); - - let byte_index = index / 8; - let byte = self.storage.as_ref()[byte_index]; - + fn extract_bit(byte: u8, index: usize) -> bool { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -34,12 +29,17 @@ where } #[inline] - pub fn set_bit(&mut self, index: usize, val: bool) { + pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; - let byte = &mut self.storage.as_mut()[byte_index]; + let byte = self.storage.as_ref()[byte_index]; + + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { @@ -48,12 +48,22 @@ where let mask = 1 << bit_index; if val { - *byte |= mask; + byte | mask } else { - *byte &= !mask; + byte & !mask } } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + + *byte = Self::change_bit(*byte, index, val); + } + #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { debug_assert!(bit_width <= 64); diff --git a/bindgen/codegen/bitfield_unit_raw_ref_macros.rs b/bindgen/codegen/bitfield_unit_raw_ref_macros.rs new file mode 100644 index 0000000000..0c864c7369 --- /dev/null +++ b/bindgen/codegen/bitfield_unit_raw_ref_macros.rs @@ -0,0 +1,191 @@ +#[repr(C)] +#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct __BindgenBitfieldUnit { + storage: Storage, +} + +impl __BindgenBitfieldUnit { + #[inline] + pub const fn new(storage: Storage) -> Self { + Self { storage } + } +} + +impl __BindgenBitfieldUnit +where + Storage: AsRef<[u8]> + AsMut<[u8]>, +{ + #[inline] + fn extract_bit(byte: u8, index: usize) -> bool { + let bit_index = if cfg!(target_endian = "big") { + 7 - (index % 8) + } else { + index % 8 + }; + + let mask = 1 << bit_index; + + byte & mask == mask + } + + #[inline] + pub fn get_bit(&self, index: usize) -> bool { + debug_assert!(index / 8 < self.storage.as_ref().len()); + + let byte_index = index / 8; + let byte = self.storage.as_ref()[byte_index]; + + Self::extract_bit(byte, index) + } + + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + + let byte_index = index / 8; + let byte = unsafe { *(core::ptr::addr_of!((*this).storage) as *const u8) + .offset(byte_index as isize) }; + + Self::extract_bit(byte, index) + } + + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { + let bit_index = if cfg!(target_endian = "big") { + 7 - (index % 8) + } else { + index % 8 + }; + + let mask = 1 << bit_index; + if val { + byte | mask + } else { + byte & !mask + } + } + + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + + *byte = Self::change_bit(*byte, index, val); + } + + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + + let byte_index = index / 8; + let byte = unsafe { + (core::ptr::addr_of_mut!((*this).storage) as *mut u8) + .offset(byte_index as isize) + }; + + unsafe { *byte = Self::change_bit(*byte, index, val) }; + } + + #[inline] + pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= + self.storage.as_ref().len() + ); + + let mut val = 0; + + for i in 0..(bit_width as usize) { + if self.get_bit(i + bit_offset) { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + + val + } + + #[inline] + pub unsafe fn raw_get( + this: *const Self, + bit_offset: usize, + bit_width: u8, + ) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= + core::mem::size_of::() + ); + + let mut val = 0; + + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + + val + } + + #[inline] + pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= + self.storage.as_ref().len() + ); + + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + self.set_bit(index + bit_offset, val_bit_is_set); + } + } + + #[inline] + pub unsafe fn raw_set( + this: *mut Self, + bit_offset: usize, + bit_width: u8, + val: u64, + ) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= + core::mem::size_of::() + ); + + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } +} diff --git a/bindgen/codegen/bitfield_unit_tests.rs b/bindgen/codegen/bitfield_unit_tests.rs index e143e4ea78..ead0ffec0c 100644 --- a/bindgen/codegen/bitfield_unit_tests.rs +++ b/bindgen/codegen/bitfield_unit_tests.rs @@ -33,7 +33,7 @@ fn bitfield_unit_get_bit() { } println!(); - println!("bits = {:?}", bits); + println!("bits = {bits:?}"); assert_eq!( bits, &[ @@ -88,8 +88,8 @@ macro_rules! bitfield_unit_get { let actual = unit.get($start, $len); println!(); - println!("expected = {:064b}", expected); - println!("actual = {:064b}", actual); + println!("expected = {expected:064b}"); + println!("actual = {actual:064b}"); assert_eq!(expected, actual); })* @@ -191,7 +191,7 @@ macro_rules! bitfield_unit_set { println!(); println!("set({}, {}, {:032b}", $start, $len, $val); println!("expected = {:064b}", $expected); - println!("actual = {:064b}", actual); + println!("actual = {actual:064b}"); assert_eq!($expected, actual); )* diff --git a/bindgen/codegen/dyngen.rs b/bindgen/codegen/dyngen.rs index c067fada0e..76f3805795 100644 --- a/bindgen/codegen/dyngen.rs +++ b/bindgen/codegen/dyngen.rs @@ -1,7 +1,7 @@ use crate::codegen; use crate::ir::context::BindgenContext; use crate::ir::function::ClangAbi; -use proc_macro2::Ident; +use proc_macro2::{Ident, TokenStream}; /// Used to build the output tokens for dynamic bindings. #[derive(Default)] @@ -14,7 +14,7 @@ pub(crate) struct DynamicItems { /// ... /// } /// ``` - struct_members: Vec, + struct_members: Vec, /// Tracks the tokens that will appear inside the library struct's implementation, e.g.: /// @@ -26,7 +26,7 @@ pub(crate) struct DynamicItems { /// } /// } /// ``` - struct_implementation: Vec, + struct_implementation: Vec, /// Tracks the initialization of the fields inside the `::new` constructor of the library /// struct, e.g.: @@ -45,7 +45,7 @@ pub(crate) struct DynamicItems { /// ... /// } /// ``` - constructor_inits: Vec, + constructor_inits: Vec, /// Tracks the information that is passed to the library struct at the end of the `::new` /// constructor, e.g.: @@ -65,7 +65,7 @@ pub(crate) struct DynamicItems { /// } /// } /// ``` - init_fields: Vec, + init_fields: Vec, } impl DynamicItems { @@ -75,14 +75,20 @@ impl DynamicItems { pub(crate) fn get_tokens( &self, - lib_ident: Ident, + lib_ident: &Ident, ctx: &BindgenContext, - ) -> proc_macro2::TokenStream { + ) -> TokenStream { let struct_members = &self.struct_members; let constructor_inits = &self.constructor_inits; let init_fields = &self.init_fields; let struct_implementation = &self.struct_implementation; + let library_new = if ctx.options().wrap_unsafe_ops { + quote!(unsafe { ::libloading::Library::new(path) }) + } else { + quote!(::libloading::Library::new(path)) + }; + let from_library = if ctx.options().wrap_unsafe_ops { quote!(unsafe { Self::from_library(library) }) } else { @@ -90,8 +96,6 @@ impl DynamicItems { }; quote! { - extern crate libloading; - pub struct #lib_ident { __library: ::libloading::Library, #(#struct_members)* @@ -102,7 +106,7 @@ impl DynamicItems { path: P ) -> Result where P: AsRef<::std::ffi::OsStr> { - let library = ::libloading::Library::new(path)?; + let library = #library_new?; #from_library } @@ -124,17 +128,18 @@ impl DynamicItems { } #[allow(clippy::too_many_arguments)] - pub(crate) fn push( + pub(crate) fn push_func( &mut self, - ident: Ident, + ident: &Ident, + symbol: &str, abi: ClangAbi, is_variadic: bool, is_required: bool, - args: Vec, - args_identifiers: Vec, - ret: proc_macro2::TokenStream, - ret_ty: proc_macro2::TokenStream, - attributes: Vec, + args: &[TokenStream], + args_identifiers: &[TokenStream], + ret: &TokenStream, + ret_ty: &TokenStream, + attributes: &[TokenStream], ctx: &BindgenContext, ) { if !is_variadic { @@ -177,11 +182,12 @@ impl DynamicItems { } // N.B: Unwrap the signature upon construction if it is required to be resolved. - let ident_str = codegen::helpers::ast_ty::cstr_expr(ident.to_string()); + let symbol_cstr = + codegen::helpers::ast_ty::cstr_expr(symbol.to_string()); let library_get = if ctx.options().wrap_unsafe_ops { - quote!(unsafe { __library.get(#ident_str) }) + quote!(unsafe { __library.get(#symbol_cstr) }) } else { - quote!(__library.get(#ident_str)) + quote!(__library.get(#symbol_cstr)) }; self.constructor_inits.push(if is_required { @@ -198,4 +204,55 @@ impl DynamicItems { #ident }); } + + pub fn push_var( + &mut self, + ident: &Ident, + symbol: &str, + ty: &TokenStream, + is_required: bool, + wrap_unsafe_ops: bool, + ) { + let member = if is_required { + quote! { *mut #ty } + } else { + quote! { Result<*mut #ty, ::libloading::Error> } + }; + + self.struct_members.push(quote! { + pub #ident: #member, + }); + + let deref = if is_required { + quote! { self.#ident } + } else { + quote! { *self.#ident.as_ref().expect("Expected variable, got error.") } + }; + self.struct_implementation.push(quote! { + pub unsafe fn #ident (&self) -> *mut #ty { + #deref + } + }); + + let symbol_cstr = + codegen::helpers::ast_ty::cstr_expr(symbol.to_string()); + + let library_get = if wrap_unsafe_ops { + quote!(unsafe { __library.get::<*mut #ty>(#symbol_cstr) }) + } else { + quote!(__library.get::<*mut #ty>(#symbol_cstr)) + }; + + let qmark = if is_required { quote!(?) } else { quote!() }; + + let var_get = quote! { + let #ident = #library_get.map(|sym| *sym)#qmark; + }; + + self.constructor_inits.push(var_get); + + self.init_fields.push(quote! { + #ident + }); + } } diff --git a/bindgen/codegen/error.rs b/bindgen/codegen/error.rs index 82e921d771..b82ba2aef1 100644 --- a/bindgen/codegen/error.rs +++ b/bindgen/codegen/error.rs @@ -36,12 +36,11 @@ impl fmt::Display for Error { Error::UnsupportedAbi(abi) => { write!( f, - "{} ABI is not supported by the configured Rust target.", - abi + "{abi} ABI is not supported by the configured Rust target." ) } Error::InvalidPointerSize { ty_name, ty_size, ptr_size } => { - write!(f, "The {} pointer type has size {} but the current target's pointer size is {}.", ty_name, ty_size, ptr_size) + write!(f, "The {ty_name} pointer type has size {ty_size} but the current target's pointer size is {ptr_size}.") } } } diff --git a/bindgen/codegen/helpers.rs b/bindgen/codegen/helpers.rs index 48bfe56dde..82172f3488 100644 --- a/bindgen/codegen/helpers.rs +++ b/bindgen/codegen/helpers.rs @@ -1,5 +1,7 @@ //! Helpers for code generation that don't need macro expansion. +use proc_macro2::{Ident, Span}; + use crate::ir::context::BindgenContext; use crate::ir::layout::Layout; @@ -17,7 +19,6 @@ pub(crate) mod attributes { pub(crate) fn repr_list(which_ones: &[&str]) -> TokenStream { let which_ones = which_ones .iter() - .cloned() .map(|one| TokenStream::from_str(one).expect("repr to be valid")); quote! { #[repr( #( #which_ones ),* )] @@ -27,7 +28,6 @@ pub(crate) mod attributes { pub(crate) fn derives(which_ones: &[&str]) -> TokenStream { let which_ones = which_ones .iter() - .cloned() .map(|one| TokenStream::from_str(one).expect("derive to be valid")); quote! { #[derive( #( #which_ones ),* )] @@ -52,7 +52,7 @@ pub(crate) mod attributes { } } - pub(crate) fn doc(comment: String) -> TokenStream { + pub(crate) fn doc(comment: &str) -> TokenStream { if comment.is_empty() { quote!() } else { @@ -66,7 +66,7 @@ pub(crate) mod attributes { let name: Cow<'_, str> = if MANGLE { name.into() } else { - format!("\u{1}{}", name).into() + format!("\u{1}{name}").into() }; quote! { @@ -75,44 +75,57 @@ pub(crate) mod attributes { } } -/// Generates a proper type for a field or type with a given `Layout`, that is, -/// a type with the correct size and alignment restrictions. -pub(crate) fn blob(ctx: &BindgenContext, layout: Layout) -> syn::Type { +/// The `ffi_safe` argument should be true if this is a type that the user might +/// reasonably use, e.g. not struct padding, where the `__BindgenOpaqueArray` is +/// just noise. +/// TODO: Should this be `MaybeUninit`, since padding bytes are effectively +/// uninitialized? +pub(crate) fn blob( + ctx: &BindgenContext, + layout: Layout, + ffi_safe: bool, +) -> syn::Type { let opaque = layout.opaque(); // FIXME(emilio, #412): We fall back to byte alignment, but there are // some things that legitimately are more than 8-byte aligned. // // Eventually we should be able to `unwrap` here, but... - let ty = match opaque.known_rust_type_for_array(ctx) { - Some(ty) => ty, - None => { - warn!("Found unknown alignment on code generation!"); - syn::parse_quote! { u8 } - } - }; + let ty = opaque.known_rust_type_for_array().unwrap_or_else(|| { + warn!("Found unknown alignment on code generation!"); + syn::parse_quote! { u8 } + }); - let data_len = opaque.array_size(ctx).unwrap_or(layout.size); + let data_len = opaque.array_size().unwrap_or(layout.size); if data_len == 1 { ty + } else if ffi_safe && ctx.options().rust_features().min_const_generics { + ctx.generated_opaque_array(); + if ctx.options().enable_cxx_namespaces { + syn::parse_quote! { root::__BindgenOpaqueArray<#ty, #data_len> } + } else { + syn::parse_quote! { __BindgenOpaqueArray<#ty, #data_len> } + } } else { + // This is not FFI safe as an argument; the struct above is + // preferable. syn::parse_quote! { [ #ty ; #data_len ] } } } /// Integer type of the same size as the given `Layout`. -pub(crate) fn integer_type( - ctx: &BindgenContext, - layout: Layout, -) -> Option { - Layout::known_type_for_size(ctx, layout.size) +pub(crate) fn integer_type(layout: Layout) -> Option { + Layout::known_type_for_size(layout.size) } +pub(crate) const BITFIELD_UNIT: &str = "__BindgenBitfieldUnit"; + /// Generates a bitfield allocation unit type for a type with the given `Layout`. pub(crate) fn bitfield_unit(ctx: &BindgenContext, layout: Layout) -> syn::Type { let size = layout.size; - let ty = syn::parse_quote! { __BindgenBitfieldUnit<[u8; #size]> }; + let bitfield_unit_name = Ident::new(BITFIELD_UNIT, Span::call_site()); + let ty = syn::parse_quote! { #bitfield_unit_name<[u8; #size]> }; if ctx.options().enable_cxx_namespaces { return syn::parse_quote! { root::#ty }; @@ -126,7 +139,8 @@ pub(crate) mod ast_ty { use crate::ir::function::FunctionSig; use crate::ir::layout::Layout; use crate::ir::ty::{FloatKind, IntKind}; - use proc_macro2::{self, TokenStream}; + use crate::RustTarget; + use proc_macro2::TokenStream; use std::str::FromStr; pub(crate) fn c_void(ctx: &BindgenContext) -> syn::Type { @@ -137,9 +151,7 @@ pub(crate) mod ast_ty { syn::parse_quote! { #prefix::c_void } } None => { - if ctx.options().use_core && - ctx.options().rust_features.core_ffi_c_void - { + if ctx.options().use_core { syn::parse_quote! { ::core::ffi::c_void } } else { syn::parse_quote! { ::std::os::raw::c_void } @@ -175,6 +187,12 @@ pub(crate) mod ast_ty { match ik { IntKind::Bool => syn::parse_quote! { bool }, IntKind::Char { .. } => raw_type(ctx, "c_char"), + // The following is used only when an unusual command-line + // argument is used. bindgen_cchar16_t is not a real type; + // but this allows downstream postprocessors to distinguish + // this case and do something special for C++ bindings + // containing the C++ type char16_t. + IntKind::Char16 => syn::parse_quote! { bindgen_cchar16_t }, IntKind::SChar => raw_type(ctx, "c_schar"), IntKind::UChar => raw_type(ctx, "c_uchar"), IntKind::Short => raw_type(ctx, "c_short"), @@ -188,7 +206,7 @@ pub(crate) mod ast_ty { IntKind::WChar => { let layout = layout.expect("Couldn't compute wchar_t's layout?"); - Layout::known_type_for_size(ctx, layout.size) + Layout::known_type_for_size(layout.size) .expect("Non-representable wchar_t?") } @@ -204,7 +222,7 @@ pub(crate) mod ast_ty { syn::parse_str(name).expect("Invalid integer type.") } IntKind::U128 => { - if ctx.options().rust_features.i128_and_u128 { + if true { syn::parse_quote! { u128 } } else { // Best effort thing, but wrong alignment @@ -213,7 +231,7 @@ pub(crate) mod ast_ty { } } IntKind::I128 => { - if ctx.options().rust_features.i128_and_u128 { + if true { syn::parse_quote! { i128 } } else { syn::parse_quote! { [u64; 2] } @@ -246,28 +264,25 @@ pub(crate) mod ast_ty { (FloatKind::Float, false) => raw_type(ctx, "c_float"), (FloatKind::Double, false) => raw_type(ctx, "c_double"), (FloatKind::LongDouble, _) => { - match layout { - Some(layout) => { - match layout.size { - 4 => syn::parse_quote! { f32 }, - 8 => syn::parse_quote! { f64 }, - // TODO(emilio): If rust ever gains f128 we should - // use it here and below. - _ => super::integer_type(ctx, layout) - .unwrap_or(syn::parse_quote! { f64 }), - } - } - None => { - debug_assert!( - false, - "How didn't we know the layout for a primitive type?" - ); - syn::parse_quote! { f64 } + if let Some(layout) = layout { + match layout.size { + 4 => syn::parse_quote! { f32 }, + 8 => syn::parse_quote! { f64 }, + // TODO(emilio): If rust ever gains f128 we should + // use it here and below. + _ => super::integer_type(layout) + .unwrap_or(syn::parse_quote! { f64 }), } + } else { + debug_assert!( + false, + "How didn't we know the layout for a primitive type?" + ); + syn::parse_quote! { f64 } } } (FloatKind::Float128, _) => { - if ctx.options().rust_features.i128_and_u128 { + if true { syn::parse_quote! { u128 } } else { syn::parse_quote! { [u64; 2] } @@ -307,26 +322,54 @@ pub(crate) mod ast_ty { } let prefix = ctx.trait_prefix(); + let rust_target = ctx.options().rust_target; if f.is_nan() { - return Ok(quote! { - ::#prefix::f64::NAN - }); + // FIXME: This should be done behind a `RustFeature` instead + #[allow(deprecated)] + let tokens = if rust_target >= RustTarget::Stable_1_43 { + quote! { + f64::NAN + } + } else { + quote! { + ::#prefix::f64::NAN + } + }; + return Ok(tokens); } if f.is_infinite() { - return Ok(if f.is_sign_positive() { - quote! { - ::#prefix::f64::INFINITY + let tokens = if f.is_sign_positive() { + // FIXME: This should be done behind a `RustFeature` instead + #[allow(deprecated)] + if rust_target >= RustTarget::Stable_1_43 { + quote! { + f64::INFINITY + } + } else { + quote! { + ::#prefix::f64::INFINITY + } } } else { - quote! { - ::#prefix::f64::NEG_INFINITY + // FIXME: This should be done behind a `RustFeature` instead + #[allow(deprecated)] + // Negative infinity + if rust_target >= RustTarget::Stable_1_43 { + quote! { + f64::NEG_INFINITY + } + } else { + quote! { + ::#prefix::f64::NEG_INFINITY + } } - }); + }; + return Ok(tokens); } - warn!("Unknown non-finite float number: {:?}", f); + warn!("Unknown non-finite float number: {f:?}"); Err(()) } @@ -338,17 +381,14 @@ pub(crate) mod ast_ty { signature .argument_types() .iter() - .map(|&(ref name, _ty)| match *name { - Some(ref name) => { - let name = ctx.rust_ident(name); - quote! { #name } - } - None => { + .map(|&(ref name, _ty)| { + let name = if let Some(ref name) = *name { + ctx.rust_ident(name) + } else { unnamed_arguments += 1; - let name = - ctx.rust_ident(format!("arg{}", unnamed_arguments)); - quote! { #name } - } + ctx.rust_ident(format!("arg{unnamed_arguments}")) + }; + quote! { #name } }) .collect() } diff --git a/bindgen/codegen/impl_debug.rs b/bindgen/codegen/impl_debug.rs index 67ec214ee8..058a73bd13 100644 --- a/bindgen/codegen/impl_debug.rs +++ b/bindgen/codegen/impl_debug.rs @@ -2,6 +2,7 @@ use crate::ir::comp::{BitfieldUnit, CompKind, Field, FieldData, FieldMethods}; use crate::ir::context::BindgenContext; use crate::ir::item::{HasTypeParamInArray, IsOpaque, Item, ItemCanonicalName}; use crate::ir::ty::{TypeKind, RUST_DERIVE_IN_ARRAY_LIMIT}; +use std::fmt::Write as _; pub(crate) fn gen_debug_impl( ctx: &BindgenContext, @@ -10,7 +11,7 @@ pub(crate) fn gen_debug_impl( kind: CompKind, ) -> proc_macro2::TokenStream { let struct_name = item.canonical_name(ctx); - let mut format_string = format!("{} {{{{ ", struct_name); + let mut format_string = format!("{struct_name} {{{{ "); let mut tokens = vec![]; if item.is_opaque(ctx, &()) { @@ -64,7 +65,7 @@ pub(crate) trait ImplDebug<'a> { ) -> Option<(String, Vec)>; } -impl<'a> ImplDebug<'a> for FieldData { +impl ImplDebug<'_> for FieldData { type Extra = (); fn impl_debug( @@ -80,7 +81,7 @@ impl<'a> ImplDebug<'a> for FieldData { } } -impl<'a> ImplDebug<'a> for BitfieldUnit { +impl ImplDebug<'_> for BitfieldUnit { type Extra = (); fn impl_debug( @@ -96,7 +97,7 @@ impl<'a> ImplDebug<'a> for BitfieldUnit { } if let Some(bitfield_name) = bitfield.name() { - format_string.push_str(&format!("{} : {{:?}}", bitfield_name)); + let _ = write!(format_string, "{bitfield_name} : {{:?}}"); let getter_name = bitfield.getter_name(); let name_ident = ctx.rust_ident_raw(getter_name); tokens.push(quote! { @@ -125,19 +126,14 @@ impl<'a> ImplDebug<'a> for Item { return None; } - let ty = match self.as_type() { - Some(ty) => ty, - None => { - return None; - } - }; + let ty = self.as_type()?; fn debug_print( name: &str, - name_ident: proc_macro2::TokenStream, + name_ident: &proc_macro2::TokenStream, ) -> Option<(String, Vec)> { Some(( - format!("{}: {{:?}}", name), + format!("{name}: {{:?}}"), vec![quote! { self.#name_ident }], @@ -158,48 +154,50 @@ impl<'a> ImplDebug<'a> for Item { TypeKind::ObjCInterface(..) | TypeKind::ObjCId | TypeKind::Comp(..) | - TypeKind::ObjCSel => debug_print(name, quote! { #name_ident }), + TypeKind::ObjCSel => debug_print(name, "e! { #name_ident }), TypeKind::TemplateInstantiation(ref inst) => { if inst.is_opaque(ctx, self) { - Some((format!("{}: opaque", name), vec![])) + Some((format!("{name}: opaque"), vec![])) } else { - debug_print(name, quote! { #name_ident }) + debug_print(name, "e! { #name_ident }) } } // The generic is not required to implement Debug, so we can not debug print that type TypeKind::TypeParam => { - Some((format!("{}: Non-debuggable generic", name), vec![])) + Some((format!("{name}: Non-debuggable generic"), vec![])) } TypeKind::Array(_, len) => { // Generics are not required to implement Debug if self.has_type_param_in_array(ctx) { - Some(( - format!("{}: Array with length {}", name, len), - vec![], - )) + Some((format!("{name}: Array with length {len}"), vec![])) } else if len < RUST_DERIVE_IN_ARRAY_LIMIT || ctx.options().rust_features().larger_arrays { // The simple case - debug_print(name, quote! { #name_ident }) + debug_print(name, "e! { #name_ident }) } else if ctx.options().use_core { // There is no String in core; reducing field visibility to avoid breaking // no_std setups. - Some((format!("{}: [...]", name), vec![])) + Some((format!("{name}: [...]"), vec![])) } else { // Let's implement our own print function Some(( - format!("{}: [{{}}]", name), - vec![quote! { - self.#name_ident - .iter() - .enumerate() - .map(|(i, v)| format!("{}{:?}", if i > 0 { ", " } else { "" }, v)) - .collect::() - }], + format!("{name}: [{{}}]"), + vec![quote! {{ + use std::fmt::Write as _; + let mut output = String::new(); + let mut iter = self.#name_ident.iter(); + if let Some(value) = iter.next() { + let _ = write!(output, "{value:?}"); + for value in iter { + let _ = write!(output, ", {value:?}"); + } + } + output + }}], )) } } @@ -207,11 +205,11 @@ impl<'a> ImplDebug<'a> for Item { if ctx.options().use_core { // There is no format! in core; reducing field visibility to avoid breaking // no_std setups. - Some((format!("{}(...)", name), vec![])) + Some((format!("{name}(...)"), vec![])) } else { let self_ids = 0..len; Some(( - format!("{}({{}})", name), + format!("{name}({{}})"), vec![quote! { #(format!("{:?}", self.#self_ids)),* }], @@ -233,9 +231,9 @@ impl<'a> ImplDebug<'a> for Item { TypeKind::Function(ref sig) if !sig.function_pointers_can_derive() => { - Some((format!("{}: FunctionPointer", name), vec![])) + Some((format!("{name}: FunctionPointer"), vec![])) } - _ => debug_print(name, quote! { #name_ident }), + _ => debug_print(name, "e! { #name_ident }), } } diff --git a/bindgen/codegen/impl_partialeq.rs b/bindgen/codegen/impl_partialeq.rs index 42fabf6ad0..c2787967d8 100644 --- a/bindgen/codegen/impl_partialeq.rs +++ b/bindgen/codegen/impl_partialeq.rs @@ -23,7 +23,7 @@ pub(crate) fn gen_partialeq_impl( &self.bindgen_union_field[..] == &other.bindgen_union_field[..] }); } else { - for base in comp_info.base_members().iter() { + for base in comp_info.base_members() { if !base.requires_storage(ctx) { continue; } @@ -76,7 +76,7 @@ fn gen_field( name: &str, ) -> proc_macro2::TokenStream { fn quote_equals( - name_ident: proc_macro2::Ident, + name_ident: &proc_macro2::Ident, ) -> proc_macro2::TokenStream { quote! { self.#name_ident == other.#name_ident } } @@ -100,7 +100,7 @@ fn gen_field( TypeKind::Comp(..) | TypeKind::Pointer(_) | TypeKind::Function(..) | - TypeKind::Opaque => quote_equals(name_ident), + TypeKind::Opaque => quote_equals(&name_ident), TypeKind::TemplateInstantiation(ref inst) => { if inst.is_opaque(ctx, ty_item) { @@ -108,7 +108,7 @@ fn gen_field( &self. #name_ident [..] == &other. #name_ident [..] } } else { - quote_equals(name_ident) + quote_equals(&name_ident) } } @@ -116,7 +116,7 @@ fn gen_field( if len <= RUST_DERIVE_IN_ARRAY_LIMIT || ctx.options().rust_features().larger_arrays { - quote_equals(name_ident) + quote_equals(&name_ident) } else { quote! { &self. #name_ident [..] == &other. #name_ident [..] diff --git a/bindgen/codegen/mod.rs b/bindgen/codegen/mod.rs index dd1486df74..8da10ff051 100644 --- a/bindgen/codegen/mod.rs +++ b/bindgen/codegen/mod.rs @@ -20,7 +20,10 @@ use self::struct_layout::StructLayoutTracker; use super::BindgenOptions; -use crate::callbacks::{DeriveInfo, FieldInfo, TypeKind as DeriveTypeKind}; +use crate::callbacks::{ + AttributeInfo, DeriveInfo, DiscoveredItem, DiscoveredItemId, FieldInfo, + TypeKind as DeriveTypeKind, +}; use crate::codegen::error::Error; use crate::ir::analysis::{HasVtable, Sizedness}; use crate::ir::annotations::{ @@ -52,8 +55,8 @@ use crate::ir::template::{ use crate::ir::ty::{Type, TypeKind}; use crate::ir::var::Var; -use proc_macro2::{self, Ident, Span}; -use quote::TokenStreamExt; +use proc_macro2::{Ident, Span}; +use quote::{ToTokens, TokenStreamExt}; use crate::{Entry, HashMap, HashSet}; use std::borrow::Cow; @@ -80,7 +83,7 @@ impl fmt::Display for CodegenError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Serialize { msg, loc } => { - write!(f, "serialization error at {}: {}", loc, msg) + write!(f, "serialization error at {loc}: {msg}") } Self::Io(err) => err.fmt(f), } @@ -149,22 +152,16 @@ fn derives_of_item( ) -> DerivableTraits { let mut derivable_traits = DerivableTraits::empty(); - let all_template_params = item.all_template_params(ctx); - if item.can_derive_copy(ctx) && !item.annotations().disallow_copy() { derivable_traits |= DerivableTraits::COPY; - if ctx.options().rust_features().builtin_clone_impls || - !all_template_params.is_empty() - { - // FIXME: This requires extra logic if you have a big array in a - // templated struct. The reason for this is that the magic: - // fn clone(&self) -> Self { *self } - // doesn't work for templates. - // - // It's not hard to fix though. - derivable_traits |= DerivableTraits::CLONE; - } + // FIXME: This requires extra logic if you have a big array in a + // templated struct. The reason for this is that the magic: + // fn clone(&self) -> Self { *self } + // doesn't work for templates. + // + // It's not hard to fix though. + derivable_traits |= DerivableTraits::CLONE; } else if packed { // If the struct or union is packed, deriving from Copy is required for // deriving from any other trait. @@ -376,7 +373,7 @@ impl<'a> CodegenResult<'a> { } } -impl<'a> ops::Deref for CodegenResult<'a> { +impl ops::Deref for CodegenResult<'_> { type Target = Vec; fn deref(&self) -> &Self::Target { @@ -384,7 +381,7 @@ impl<'a> ops::Deref for CodegenResult<'a> { } } -impl<'a> ops::DerefMut for CodegenResult<'a> { +impl ops::DerefMut for CodegenResult<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.items } @@ -507,7 +504,7 @@ impl Item { // TODO(emilio, #453): Figure out what to do when this happens // legitimately, we could track the opaque stuff and disable the // assertion there I guess. - warn!("Found non-allowlisted item in code generation: {:?}", self); + warn!("Found non-allowlisted item in code generation: {self:?}"); } result.set_seen(self.id()); @@ -525,7 +522,7 @@ impl CodeGenerator for Item { result: &mut CodegenResult<'_>, _extra: &(), ) { - debug!("::codegen: self = {:?}", self); + debug!("::codegen: self = {self:?}"); if !self.process_before_codegen(ctx, result) { return; } @@ -557,7 +554,7 @@ impl CodeGenerator for Module { result: &mut CodegenResult<'_>, item: &Item, ) { - debug!("::codegen: item = {:?}", item); + debug!("::codegen: item = {item:?}"); let codegen_self = |result: &mut CodegenResult, found_any: &mut bool| { @@ -584,6 +581,9 @@ impl CodeGenerator for Module { if ctx.need_bindgen_complex_type() { utils::prepend_complex_type(&mut *result); } + if ctx.need_opaque_array_type() { + utils::prepend_opaque_array_type(&mut *result); + } if result.saw_objc { utils::prepend_objc_header(ctx, &mut *result); } @@ -656,7 +656,7 @@ impl CodeGenerator for Var { item: &Item, ) { use crate::ir::var::VarType; - debug!("::codegen: item = {:?}", item); + debug!("::codegen: item = {item:?}"); debug_assert!(item.is_enabled_for_codegen(ctx)); let canonical_name = item.canonical_name(ctx); @@ -677,7 +677,7 @@ impl CodeGenerator for Var { let mut attrs = vec![]; if let Some(comment) = item.comment(ctx) { - attrs.push(attributes::doc(comment)); + attrs.push(attributes::doc(&comment)); } let var_ty = self.ty(); @@ -721,33 +721,41 @@ impl CodeGenerator for Var { let len = proc_macro2::Literal::usize_unsuffixed( cstr_bytes.len(), ); - - // TODO: Here we ignore the type we just made up, probably - // we should refactor how the variable type and ty ID work. - let array_ty = quote! { [u8; #len] }; - let cstr_ty = quote! { ::#prefix::ffi::CStr }; - - let bytes = proc_macro2::Literal::byte_string(&cstr_bytes); - - if options.generate_cstr && - rust_features.const_cstr && - CStr::from_bytes_with_nul(&cstr_bytes).is_ok() - { - result.push(quote! { - #(#attrs)* - #[allow(unsafe_code)] - pub const #canonical_ident: &#cstr_ty = unsafe { - #cstr_ty::from_bytes_with_nul_unchecked(#bytes) - }; - }); - } else { - let lifetime = if rust_features.static_lifetime_elision - { + let cstr = + if options.generate_cstr && rust_features.const_cstr { + CStr::from_bytes_with_nul(&cstr_bytes).ok() + } else { None + }; + + if let Some(cstr) = cstr { + let cstr_ty = quote! { ::#prefix::ffi::CStr }; + if rust_features.literal_cstr { + let cstr = proc_macro2::Literal::c_string(cstr); + result.push(quote! { + #(#attrs)* + pub const #canonical_ident: &#cstr_ty = #cstr; + }); } else { - Some(quote! { 'static }) + let bytes = + proc_macro2::Literal::byte_string(&cstr_bytes); + result.push(quote! { + #(#attrs)* + #[allow(unsafe_code)] + pub const #canonical_ident: &#cstr_ty = unsafe { + #cstr_ty::from_bytes_with_nul_unchecked(#bytes) + }; + }); } - .into_iter(); + } else { + // TODO: Here we ignore the type we just made up, probably + // we should refactor how the variable type and ty ID work. + let array_ty = quote! { [u8; #len] }; + let bytes = + proc_macro2::Literal::byte_string(&cstr_bytes); + let lifetime = + if true { None } else { Some(quote! { 'static }) } + .into_iter(); result.push(quote! { #(#attrs)* @@ -771,20 +779,20 @@ impl CodeGenerator for Var { } } } else { - // If necessary, apply a `#[link_name]` attribute - if let Some(link_name) = self.link_name() { - attrs.push(attributes::link_name::(link_name)); - } else { + let symbol: &str = self.link_name().unwrap_or_else(|| { let link_name = self.mangled_name().unwrap_or_else(|| self.name()); - if !utils::names_will_be_identical_after_mangling( + if utils::names_will_be_identical_after_mangling( &canonical_name, link_name, None, ) { + canonical_name.as_str() + } else { attrs.push(attributes::link_name::(link_name)); + link_name } - } + }); let maybe_mut = if self.is_const() { quote! {} @@ -792,14 +800,33 @@ impl CodeGenerator for Var { quote! { mut } }; + let safety = ctx + .options() + .rust_features + .unsafe_extern_blocks + .then(|| quote!(unsafe)); + let tokens = quote!( - extern "C" { + #safety extern "C" { #(#attrs)* pub static #maybe_mut #canonical_ident: #ty; } ); - result.push(tokens); + if ctx.options().dynamic_library_name.is_some() { + result.dynamic_items().push_var( + &canonical_ident, + symbol, + &self + .ty() + .to_rust_ty_or_opaque(ctx, &()) + .into_token_stream(), + ctx.options().dynamic_link_require_all, + ctx.options().wrap_unsafe_ops, + ); + } else { + result.push(tokens); + } } } } @@ -814,7 +841,7 @@ impl CodeGenerator for Type { result: &mut CodegenResult<'_>, item: &Item, ) { - debug!("::codegen: item = {:?}", item); + debug!("::codegen: item = {item:?}"); debug_assert!(item.is_enabled_for_codegen(ctx)); match *self.kind() { @@ -837,7 +864,7 @@ impl CodeGenerator for Type { // it to BindgenContext::compute_allowlisted_and_codegen_items. } TypeKind::TemplateInstantiation(ref inst) => { - inst.codegen(ctx, result, item) + inst.codegen(ctx, result, item); } TypeKind::BlockPointer(inner) => { if !ctx.options().generate_block { @@ -854,14 +881,14 @@ impl CodeGenerator for Type { { utils::fnsig_block(ctx, fnsig) } else { - panic!("invalid block typedef: {:?}", inner_item) + panic!("invalid block typedef: {inner_item:?}") } }; let rust_name = ctx.rust_ident(name); let mut tokens = if let Some(comment) = item.comment(ctx) { - attributes::doc(comment) + attributes::doc(&comment) } else { quote! {} }; @@ -912,16 +939,14 @@ impl CodeGenerator for Type { assert_eq!( layout.size, ctx.target_pointer_size(), - "Target platform requires `--no-size_t-is-usize`. The size of `{}` ({}) does not match the target pointer size ({})", - spelling, + "Target platform requires `--no-size_t-is-usize`. The size of `{spelling}` ({}) does not match the target pointer size ({})", layout.size, ctx.target_pointer_size(), ); assert_eq!( layout.align, ctx.target_pointer_size(), - "Target platform requires `--no-size_t-is-usize`. The alignment of `{}` ({}) does not match the target pointer size ({})", - spelling, + "Target platform requires `--no-size_t-is-usize`. The alignment of `{spelling}` ({}) does not match the target pointer size ({})", layout.align, ctx.target_pointer_size(), ); @@ -970,8 +995,20 @@ impl CodeGenerator for Type { let rust_name = ctx.rust_ident(&name); + ctx.options().for_each_callback(|cb| { + cb.new_item_found( + DiscoveredItemId::new(item.id().as_usize()), + DiscoveredItem::Alias { + alias_name: rust_name.to_string(), + alias_for: DiscoveredItemId::new( + inner_item.id().as_usize(), + ), + }, + ); + }); + let mut tokens = if let Some(comment) = item.comment(ctx) { - attributes::doc(comment) + attributes::doc(&comment) } else { quote! {} }; @@ -1011,21 +1048,38 @@ impl CodeGenerator for Type { pub type #rust_name }, AliasVariation::NewType | AliasVariation::NewTypeDeref => { - assert!( - ctx.options().rust_features().repr_transparent, - "repr_transparent feature is required to use {:?}", - alias_style - ); - let mut attributes = vec![attributes::repr("transparent")]; let packed = false; // Types can't be packed in Rust. let derivable_traits = derives_of_item(item, ctx, packed); - if !derivable_traits.is_empty() { - let derives: Vec<_> = derivable_traits.into(); - attributes.push(attributes::derives(&derives)) - } + let mut derives: Vec<_> = derivable_traits.into(); + // The custom derives callback may return a list of derive attributes; + // add them to the end of the list. + let custom_derives = + ctx.options().all_callbacks(|cb| { + cb.add_derives(&DeriveInfo { + name: &name, + kind: DeriveTypeKind::Struct, + }) + }); + // In most cases this will be a no-op, since custom_derives will be empty. + derives + .extend(custom_derives.iter().map(|s| s.as_str())); + attributes.push(attributes::derives(&derives)); + + let custom_attributes = + ctx.options().all_callbacks(|cb| { + cb.add_attributes(&AttributeInfo { + name: &name, + kind: DeriveTypeKind::Struct, + }) + }); + attributes.extend( + custom_attributes + .iter() + .map(|s| s.parse().unwrap()), + ); quote! { #( #attributes )* @@ -1064,13 +1118,24 @@ impl CodeGenerator for Type { }); } - let access_spec = - access_specifier(ctx.options().default_visibility); tokens.append_all(match alias_style { AliasVariation::TypeAlias => quote! { = #inner_rust_type ; }, AliasVariation::NewType | AliasVariation::NewTypeDeref => { + let visibility = ctx + .options() + .last_callback(|cb| { + cb.field_visibility(FieldInfo { + type_name: &item.canonical_name(ctx), + field_name: "0", + field_type_name: inner_item + .expect_type() + .name(), + }) + }) + .unwrap_or(ctx.options().default_visibility); + let access_spec = access_specifier(visibility); quote! { (#access_spec #inner_rust_type) ; } @@ -1103,10 +1168,10 @@ impl CodeGenerator for Type { result.saw_objc(); } TypeKind::ObjCInterface(ref interface) => { - interface.codegen(ctx, result, item) + interface.codegen(ctx, result, item); } ref u @ TypeKind::UnresolvedTypeRef(..) => { - unreachable!("Should have been resolved after parsing {:?}!", u) + unreachable!("Should have been resolved after parsing {u:?}!") } } } @@ -1125,7 +1190,7 @@ impl<'a> Vtable<'a> { } } -impl<'a> CodeGenerator for Vtable<'a> { +impl CodeGenerator for Vtable<'_> { type Extra = Item; type Return = (); @@ -1160,10 +1225,7 @@ impl<'a> CodeGenerator for Vtable<'a> { let function_item = ctx.resolve_item(m.signature()); let function = function_item.expect_function(); let signature_item = ctx.resolve_item(function.signature()); - let signature = match signature_item.expect_type().kind() { - TypeKind::Function(ref sig) => sig, - _ => panic!("Function signature type mismatch"), - }; + let TypeKind::Function(ref signature) = signature_item.expect_type().kind() else { panic!("Function signature type mismatch") }; // FIXME: Is there a canonical name without the class prepended? let function_name = function_item.canonical_name(ctx); @@ -1190,7 +1252,7 @@ impl<'a> CodeGenerator for Vtable<'a> { pub struct #name { #( #methods ),* } - }) + }); } else { // For the cases we don't support, simply generate an empty struct. let void = helpers::ast_ty::c_void(ctx); @@ -1203,13 +1265,13 @@ impl<'a> CodeGenerator for Vtable<'a> { } } -impl<'a> ItemCanonicalName for Vtable<'a> { +impl ItemCanonicalName for Vtable<'_> { fn canonical_name(&self, ctx: &BindgenContext) -> String { format!("{}__bindgen_vtable", self.item_id.canonical_name(ctx)) } } -impl<'a> TryToRustTy for Vtable<'a> { +impl TryToRustTy for Vtable<'_> { type Extra = (); fn try_to_rust_ty( @@ -1244,6 +1306,9 @@ impl CodeGenerator for TemplateInstantiation { return; } + // For consistency with other layout tests, gate this on offset_of. + let compile_time = ctx.options().rust_features().offset_of; + // If there are any unbound type parameters, then we can't generate a // layout test because we aren't dealing with a concrete type with a // concrete size and alignment. @@ -1258,14 +1323,17 @@ impl CodeGenerator for TemplateInstantiation { let align = layout.align; let name = item.full_disambiguated_name(ctx); - let mut fn_name = - format!("__bindgen_test_layout_{}_instantiation", name); - let times_seen = result.overload_number(&fn_name); - if times_seen > 0 { - write!(&mut fn_name, "_{}", times_seen).unwrap(); - } - - let fn_name = ctx.rust_ident_raw(fn_name); + let fn_name = if compile_time { + None + } else { + let mut fn_name = + format!("__bindgen_test_layout_{name}_instantiation"); + let times_seen = result.overload_number(&fn_name); + if times_seen > 0 { + write!(&mut fn_name, "_{times_seen}").unwrap(); + } + Some(ctx.rust_ident_raw(fn_name)) + }; let prefix = ctx.trait_prefix(); let ident = item.to_rust_ty_or_opaque(ctx, &()); @@ -1275,20 +1343,33 @@ impl CodeGenerator for TemplateInstantiation { let align_of_expr = quote! { ::#prefix::mem::align_of::<#ident>() }; - - let item = quote! { - #[test] - fn #fn_name() { - assert_eq!(#size_of_expr, #size, - concat!("Size of template specialization: ", - stringify!(#ident))); - assert_eq!(#align_of_expr, #align, - concat!("Alignment of template specialization: ", - stringify!(#ident))); - } - }; - - result.push(item); + let size_of_err = + format!("Size of template specialization: {name}"); + let align_of_err = + format!("Align of template specialization: {name}"); + + if compile_time { + // In an ideal world this would be assert_eq!, but that is not + // supported in const fn due to the need for string formatting. + // If #size_of_expr > #size, this will index OOB, and if + // #size_of_expr < #size, the subtraction will overflow, both + // of which print enough information to see what has gone wrong. + result.push(quote! { + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [#size_of_err][#size_of_expr - #size]; + [#align_of_err][#align_of_expr - #align]; + }; + }); + } else { + result.push(quote! { + #[test] + fn #fn_name() { + assert_eq!(#size_of_expr, #size, #size_of_err); + assert_eq!(#align_of_expr, #align, #align_of_err); + } + }); + } } } } @@ -1305,6 +1386,7 @@ trait FieldCodegen<'a> { accessor_kind: FieldAccessorKind, parent: &CompInfo, parent_item: &Item, + last_field: bool, result: &mut CodegenResult, struct_layout: &mut StructLayoutTracker, fields: &mut F, @@ -1315,7 +1397,7 @@ trait FieldCodegen<'a> { M: Extend; } -impl<'a> FieldCodegen<'a> for Field { +impl FieldCodegen<'_> for Field { type Extra = (); fn codegen( @@ -1325,6 +1407,7 @@ impl<'a> FieldCodegen<'a> for Field { accessor_kind: FieldAccessorKind, parent: &CompInfo, parent_item: &Item, + last_field: bool, result: &mut CodegenResult, struct_layout: &mut StructLayoutTracker, fields: &mut F, @@ -1342,6 +1425,7 @@ impl<'a> FieldCodegen<'a> for Field { accessor_kind, parent, parent_item, + last_field, result, struct_layout, fields, @@ -1356,6 +1440,7 @@ impl<'a> FieldCodegen<'a> for Field { accessor_kind, parent, parent_item, + last_field, result, struct_layout, fields, @@ -1390,7 +1475,7 @@ fn wrap_union_field_if_needed( } } -impl<'a> FieldCodegen<'a> for FieldData { +impl FieldCodegen<'_> for FieldData { type Extra = (); fn codegen( @@ -1400,6 +1485,7 @@ impl<'a> FieldCodegen<'a> for FieldData { accessor_kind: FieldAccessorKind, parent: &CompInfo, parent_item: &Item, + last_field: bool, result: &mut CodegenResult, struct_layout: &mut StructLayoutTracker, fields: &mut F, @@ -1425,14 +1511,20 @@ impl<'a> FieldCodegen<'a> for FieldData { let ty = if parent.is_union() { wrap_union_field_if_needed(ctx, struct_layout, ty, result) } else if let Some(item) = field_ty.is_incomplete_array(ctx) { - result.saw_incomplete_array(); + // Only FAM if its the last field + if ctx.options().flexarray_dst && last_field { + struct_layout.saw_flexible_array(); + syn::parse_quote! { FAM } + } else { + result.saw_incomplete_array(); - let inner = item.to_rust_ty_or_opaque(ctx, &()); + let inner = item.to_rust_ty_or_opaque(ctx, &()); - if ctx.options().enable_cxx_namespaces { - syn::parse_quote! { root::__IncompleteArrayField<#inner> } - } else { - syn::parse_quote! { __IncompleteArrayField<#inner> } + if ctx.options().enable_cxx_namespaces { + syn::parse_quote! { root::__IncompleteArrayField<#inner> } + } else { + syn::parse_quote! { __IncompleteArrayField<#inner> } + } } } else { ty @@ -1442,7 +1534,7 @@ impl<'a> FieldCodegen<'a> for FieldData { if ctx.options().generate_comments { if let Some(raw_comment) = self.comment() { let comment = ctx.options().process_comment(raw_comment); - field = attributes::doc(comment); + field = attributes::doc(&comment); } } @@ -1466,6 +1558,7 @@ impl<'a> FieldCodegen<'a> for FieldData { cb.field_visibility(FieldInfo { type_name: &parent_item.canonical_name(ctx), field_name, + field_type_name: field_ty.name(), }) }), self.annotations(), @@ -1499,9 +1592,9 @@ impl<'a> FieldCodegen<'a> for FieldData { return; } - let getter_name = ctx.rust_ident_raw(format!("get_{}", field_name)); + let getter_name = ctx.rust_ident_raw(format!("get_{field_name}")); let mutable_getter_name = - ctx.rust_ident_raw(format!("get_{}_mut", field_name)); + ctx.rust_ident_raw(format!("get_{field_name}_mut")); methods.extend(Some(match accessor_kind { FieldAccessorKind::None => unreachable!(), @@ -1563,18 +1656,17 @@ impl Bitfield { fn extend_ctor_impl( &self, ctx: &BindgenContext, - param_name: proc_macro2::TokenStream, + param_name: &proc_macro2::TokenStream, mut ctor_impl: proc_macro2::TokenStream, ) -> proc_macro2::TokenStream { let bitfield_ty = ctx.resolve_type(self.ty()); let bitfield_ty_layout = bitfield_ty .layout(ctx) .expect("Bitfield without layout? Gah!"); - let bitfield_int_ty = helpers::integer_type(ctx, bitfield_ty_layout) - .expect( - "Should already have verified that the bitfield is \ + let bitfield_int_ty = helpers::integer_type(bitfield_ty_layout).expect( + "Should already have verified that the bitfield is \ representable as an int", - ); + ); let offset = self.offset_into_unit(); let width = self.width() as u8; @@ -1609,13 +1701,13 @@ fn access_specifier( /// Compute a fields or structs visibility based on multiple conditions. /// 1. If the element was declared public, and we respect such CXX accesses specs -/// (context option) => By default Public, but this can be overruled by an `annotation`. +/// (context option) => By default Public, but this can be overruled by an `annotation`. /// /// 2. If the element was declared private, and we respect such CXX accesses specs -/// (context option) => By default Private, but this can be overruled by an `annotation`. +/// (context option) => By default Private, but this can be overruled by an `annotation`. /// /// 3. If we do not respect visibility modifiers, the result depends on the `annotation`, -/// if any, or the passed `default_kind`. +/// if any, or the passed `default_kind`. /// fn compute_visibility( ctx: &BindgenContext, @@ -1644,7 +1736,7 @@ fn compute_visibility( }) } -impl<'a> FieldCodegen<'a> for BitfieldUnit { +impl FieldCodegen<'_> for BitfieldUnit { type Extra = (); fn codegen( @@ -1654,6 +1746,7 @@ impl<'a> FieldCodegen<'a> for BitfieldUnit { accessor_kind: FieldAccessorKind, parent: &CompInfo, parent_item: &Item, + last_field: bool, result: &mut CodegenResult, struct_layout: &mut StructLayoutTracker, fields: &mut F, @@ -1714,7 +1807,8 @@ impl<'a> FieldCodegen<'a> for BitfieldUnit { let mut generate_ctor = layout.size <= RUST_DERIVE_IN_ARRAY_LIMIT; let mut unit_visibility = visibility_kind; - for bf in self.bitfields() { + let bfields = self.bitfields(); + for (idx, bf) in bfields.iter().enumerate() { // Codegen not allowed for anonymous bitfields if bf.name().is_none() { continue; @@ -1734,12 +1828,14 @@ impl<'a> FieldCodegen<'a> for BitfieldUnit { accessor_kind, parent, parent_item, + last_field && idx == bfields.len() - 1, result, struct_layout, fields, methods, ( &unit_field_name, + &unit_field_ty, &mut bitfield_representable_as_int, &mut bitfield_visibility, ), @@ -1763,7 +1859,7 @@ impl<'a> FieldCodegen<'a> for BitfieldUnit { ctor_params.push(quote! { #param_name : #bitfield_ty }); - ctor_impl = bf.extend_ctor_impl(ctx, param_name, ctor_impl); + ctor_impl = bf.extend_ctor_impl(ctx, ¶m_name, ctor_impl); } let access_spec = access_specifier(unit_visibility); @@ -1797,6 +1893,15 @@ fn bitfield_getter_name( quote! { #name } } +fn bitfield_raw_getter_name( + ctx: &BindgenContext, + bitfield: &Bitfield, +) -> proc_macro2::TokenStream { + let name = bitfield.getter_name(); + let name = ctx.rust_ident_raw(format!("{name}_raw")); + quote! { #name } +} + fn bitfield_setter_name( ctx: &BindgenContext, bitfield: &Bitfield, @@ -1806,8 +1911,22 @@ fn bitfield_setter_name( quote! { #setter } } +fn bitfield_raw_setter_name( + ctx: &BindgenContext, + bitfield: &Bitfield, +) -> proc_macro2::TokenStream { + let setter = bitfield.setter_name(); + let setter = ctx.rust_ident_raw(format!("{setter}_raw")); + quote! { #setter } +} + impl<'a> FieldCodegen<'a> for Bitfield { - type Extra = (&'a str, &'a mut bool, &'a mut FieldVisibilityKind); + type Extra = ( + &'a str, + &'a syn::Type, + &'a mut bool, + &'a mut FieldVisibilityKind, + ); fn codegen( &self, @@ -1816,12 +1935,19 @@ impl<'a> FieldCodegen<'a> for Bitfield { _accessor_kind: FieldAccessorKind, parent: &CompInfo, parent_item: &Item, + _last_field: bool, _result: &mut CodegenResult, struct_layout: &mut StructLayoutTracker, _fields: &mut F, methods: &mut M, - (unit_field_name, bitfield_representable_as_int, bitfield_visibility): ( + ( + unit_field_name, + unit_field_ty, + bitfield_representable_as_int, + bitfield_visibility, + ): ( &'a str, + &'a syn::Type, &mut bool, &'a mut FieldVisibilityKind, ), @@ -1832,24 +1958,24 @@ impl<'a> FieldCodegen<'a> for Bitfield { let prefix = ctx.trait_prefix(); let getter_name = bitfield_getter_name(ctx, self); let setter_name = bitfield_setter_name(ctx, self); + let raw_getter_name = bitfield_raw_getter_name(ctx, self); + let raw_setter_name = bitfield_raw_setter_name(ctx, self); let unit_field_ident = Ident::new(unit_field_name, Span::call_site()); let bitfield_ty_item = ctx.resolve_item(self.ty()); let bitfield_ty = bitfield_ty_item.expect_type(); + let bitfield_ty_ident = bitfield_ty.name(); let bitfield_ty_layout = bitfield_ty .layout(ctx) .expect("Bitfield without layout? Gah!"); let bitfield_int_ty = - match helpers::integer_type(ctx, bitfield_ty_layout) { - Some(int_ty) => { - *bitfield_representable_as_int = true; - int_ty - } - None => { - *bitfield_representable_as_int = false; - return; - } + if let Some(int_ty) = helpers::integer_type(bitfield_ty_layout) { + *bitfield_representable_as_int = true; + int_ty + } else { + *bitfield_representable_as_int = false; + return; }; let bitfield_ty = @@ -1863,6 +1989,7 @@ impl<'a> FieldCodegen<'a> for Bitfield { cb.field_visibility(FieldInfo { type_name: &parent_item.canonical_name(ctx), field_name, + field_type_name: bitfield_ty_ident, }) }) }); @@ -1899,6 +2026,34 @@ impl<'a> FieldCodegen<'a> for Bitfield { } } })); + + if ctx.options().rust_features.raw_ref_macros { + methods.extend(Some(quote! { + #[inline] + #access_spec unsafe fn #raw_getter_name(this: *const Self) -> #bitfield_ty { + unsafe { + ::#prefix::mem::transmute(<#unit_field_ty>::raw_get( + (*::#prefix::ptr::addr_of!((*this).#unit_field_ident)).as_ref() as *const _, + #offset, + #width, + ) as #bitfield_int_ty) + } + } + + #[inline] + #access_spec unsafe fn #raw_setter_name(this: *mut Self, val: #bitfield_ty) { + unsafe { + let val: #bitfield_int_ty = ::#prefix::mem::transmute(val); + <#unit_field_ty>::raw_set( + (*::#prefix::ptr::addr_of_mut!((*this).#unit_field_ident)).as_mut() as *mut _, + #offset, + #width, + val as u64, + ) + } + } + })); + } } else { methods.extend(Some(quote! { #[inline] @@ -1923,6 +2078,34 @@ impl<'a> FieldCodegen<'a> for Bitfield { } } })); + + if ctx.options().rust_features.raw_ref_macros { + methods.extend(Some(quote! { + #[inline] + #access_spec unsafe fn #raw_getter_name(this: *const Self) -> #bitfield_ty { + unsafe { + ::#prefix::mem::transmute(<#unit_field_ty>::raw_get( + ::#prefix::ptr::addr_of!((*this).#unit_field_ident), + #offset, + #width, + ) as #bitfield_int_ty) + } + } + + #[inline] + #access_spec unsafe fn #raw_setter_name(this: *mut Self, val: #bitfield_ty) { + unsafe { + let val: #bitfield_int_ty = ::#prefix::mem::transmute(val); + <#unit_field_ty>::raw_set( + ::#prefix::ptr::addr_of_mut!((*this).#unit_field_ident), + #offset, + #width, + val as u64, + ) + } + } + })); + } } } } @@ -1937,7 +2120,7 @@ impl CodeGenerator for CompInfo { result: &mut CodegenResult<'_>, item: &Item, ) { - debug!("::codegen: item = {:?}", item); + debug!("::codegen: item = {item:?}"); debug_assert!(item.is_enabled_for_codegen(ctx)); // Don't output classes with template parameters that aren't types, and @@ -1980,6 +2163,23 @@ impl CodeGenerator for CompInfo { packed, ); + let mut generic_param_names = vec![]; + + for (idx, ty) in item.used_template_params(ctx).iter().enumerate() { + let param = ctx.resolve_type(*ty); + let name = param.name().unwrap(); + let ident = ctx.rust_ident(name); + generic_param_names.push(ident.clone()); + + let prefix = ctx.trait_prefix(); + let field_name = ctx.rust_ident(format!("_phantom_{idx}")); + fields.push(quote! { + pub #field_name : ::#prefix::marker::PhantomData< + ::#prefix::cell::UnsafeCell<#ident> + > , + }); + } + if !is_opaque { if item.has_vtable_ptr(ctx) { let vtable = Vtable::new(item.id(), self); @@ -2032,13 +2232,15 @@ impl CodeGenerator for CompInfo { .annotations() .accessor_kind() .unwrap_or(FieldAccessorKind::None); - for field in self.fields() { + let field_decls = self.fields(); + for (idx, field) in field_decls.iter().enumerate() { field.codegen( ctx, visibility, struct_accessor_kind, self, item, + idx == field_decls.len() - 1, result, &mut struct_layout, &mut fields, @@ -2090,7 +2292,7 @@ impl CodeGenerator for CompInfo { if has_address { let layout = Layout::new(1, 1); - let ty = helpers::blob(ctx, Layout::new(1, 1)); + let ty = helpers::blob(ctx, Layout::new(1, 1), false); struct_layout.saw_field_with_layout( "_address", layout, @@ -2107,13 +2309,15 @@ impl CodeGenerator for CompInfo { Some(l) => { explicit_align = Some(l.align); - let ty = helpers::blob(ctx, l); + let ty = helpers::blob(ctx, l, false); fields.push(quote! { pub _bindgen_opaque_blob: #ty , }); } None => { - warn!("Opaque type without layout! Expect dragons!"); + if !forward_decl { + warn!("Opaque type without layout! Expect dragons!"); + } } } } else if !is_union && !zero_sized { @@ -2129,15 +2333,6 @@ impl CodeGenerator for CompInfo { packed = true; } else { explicit_align = Some(layout.align); - if !ctx.options().rust_features.repr_align { - let ty = helpers::blob( - ctx, - Layout::new(0, layout.align), - ); - fields.push(quote! { - pub __bindgen_align: #ty , - }); - } } } } @@ -2150,10 +2345,10 @@ impl CodeGenerator for CompInfo { } if !struct_layout.is_rust_union() { - let ty = helpers::blob(ctx, layout); + let ty = helpers::blob(ctx, layout, false); fields.push(quote! { pub bindgen_union_field: #ty , - }) + }); } } @@ -2163,39 +2358,62 @@ impl CodeGenerator for CompInfo { }); } - let mut generic_param_names = vec![]; - - for (idx, ty) in item.used_template_params(ctx).iter().enumerate() { - let param = ctx.resolve_type(*ty); - let name = param.name().unwrap(); - let ident = ctx.rust_ident(name); - generic_param_names.push(ident.clone()); - - let prefix = ctx.trait_prefix(); - let field_name = ctx.rust_ident(format!("_phantom_{}", idx)); - fields.push(quote! { - pub #field_name : ::#prefix::marker::PhantomData< - ::#prefix::cell::UnsafeCell<#ident> - > , - }); - } - - let generics = if !generic_param_names.is_empty() { - let generic_param_names = generic_param_names.clone(); - quote! { - < #( #generic_param_names ),* > + let (flex_array_generic, flex_inner_ty) = if ctx.options().flexarray_dst + { + match self.flex_array_member(ctx) { + Some(ty) => { + let inner = ty.to_rust_ty_or_opaque(ctx, &()); + ( + Some(quote! { FAM: ?Sized = [ #inner; 0 ] }), + Some(quote! { #inner }), + ) + } + None => (None, None), } } else { - quote! {} + (None, None) }; + // Generics, including the flexible array member. + // + // generics - generic parameters for the struct declaration + // impl_generics_labels - generic parameters for `impl<...>` + // impl_generics_params - generic parameters for `impl structname<...>` + // + // `impl` blocks are for non-FAM related impls like Default, etc + let (generics, impl_generics_labels, impl_generics_params) = + if !generic_param_names.is_empty() || flex_array_generic.is_some() { + let (flex_sized, flex_fam) = match flex_inner_ty.as_ref() { + None => (None, None), + Some(ty) => ( + Some(quote! { [ #ty; 0 ] }), + Some(quote! { FAM: ?Sized = [ #ty; 0 ] }), + ), + }; + + ( + quote! { + < #( #generic_param_names , )* #flex_fam > + }, + quote! { + < #( #generic_param_names , )* > + }, + quote! { + < #( #generic_param_names , )* #flex_sized > + }, + ) + } else { + (quote! {}, quote! {}, quote! {}) + }; + let mut attributes = vec![]; let mut needs_clone_impl = false; let mut needs_default_impl = false; let mut needs_debug_impl = false; let mut needs_partialeq_impl = false; + let needs_flexarray_impl = flex_array_generic.is_some(); if let Some(comment) = item.comment(ctx) { - attributes.push(attributes::doc(comment)); + attributes.push(attributes::doc(&comment)); } // if a type has both a "packed" attribute and an "align(N)" attribute, then check if the @@ -2210,14 +2428,14 @@ impl CodeGenerator for CompInfo { let packed_repr = if n == 1 { "packed".to_string() } else { - format!("packed({})", n) + format!("packed({n})") }; attributes.push(attributes::repr_list(&["C", &packed_repr])); } else { attributes.push(attributes::repr("C")); } - if ctx.options().rust_features().repr_align { + if true { if let Some(explicit) = explicit_align { // Ensure that the struct has the correct alignment even in // presence of alignas. @@ -2263,6 +2481,30 @@ impl CodeGenerator for CompInfo { let is_rust_union = is_union && struct_layout.is_rust_union(); + let discovered_id = DiscoveredItemId::new(item.id().as_usize()); + ctx.options().for_each_callback(|cb| { + let discovered_item = match self.kind() { + CompKind::Struct => DiscoveredItem::Struct { + original_name: item + .kind() + .expect_type() + .name() + .map(String::from), + final_name: canonical_ident.to_string(), + }, + CompKind::Union => DiscoveredItem::Union { + original_name: item + .kind() + .expect_type() + .name() + .map(String::from), + final_name: canonical_ident.to_string(), + }, + }; + + cb.new_item_found(discovered_id, discovered_item); + }); + // The custom derives callback may return a list of derive attributes; // add them to the end of the list. let custom_derives = ctx.options().all_callbacks(|cb| { @@ -2279,9 +2521,28 @@ impl CodeGenerator for CompInfo { derives.extend(custom_derives.iter().map(|s| s.as_str())); if !derives.is_empty() { - attributes.push(attributes::derives(&derives)) + attributes.push(attributes::derives(&derives)); } + attributes.extend( + item.annotations() + .attributes() + .iter() + .map(|s| s.parse().unwrap()), + ); + + let custom_attributes = ctx.options().all_callbacks(|cb| { + cb.add_attributes(&AttributeInfo { + name: &canonical_name, + kind: if is_rust_union { + DeriveTypeKind::Union + } else { + DeriveTypeKind::Struct + }, + }) + }); + attributes.extend(custom_attributes.iter().map(|s| s.parse().unwrap())); + if item.must_use(ctx) { attributes.push(attributes::must_use()); } @@ -2319,10 +2580,7 @@ impl CodeGenerator for CompInfo { // affect layout, so we're bad and pray to the gods for avoid sending // all the tests to shit when parsing things like max_align_t. if self.found_unknown_attr() { - warn!( - "Type {} has an unknown attribute that may affect layout", - canonical_ident - ); + warn!("Type {canonical_ident} has an unknown attribute that may affect layout"); } if all_template_params.is_empty() { @@ -2334,9 +2592,14 @@ impl CodeGenerator for CompInfo { if ctx.options().layout_tests && !self.is_forward_declaration() { if let Some(layout) = layout { - let fn_name = - format!("bindgen_test_layout_{}", canonical_ident); - let fn_name = ctx.rust_ident_raw(fn_name); + let compile_time = ctx.options().rust_features().offset_of; + let fn_name = if compile_time { + None + } else { + let fn_name = + format!("bindgen_test_layout_{canonical_ident}"); + Some(ctx.rust_ident_raw(fn_name)) + }; let prefix = ctx.trait_prefix(); let size_of_expr = quote! { ::#prefix::mem::size_of::<#canonical_ident>() @@ -2346,19 +2609,18 @@ impl CodeGenerator for CompInfo { }; let size = layout.size; let align = layout.align; + let size_of_err = format!("Size of {canonical_ident}"); + let align_of_err = + format!("Alignment of {canonical_ident}"); - let check_struct_align = if align > - ctx.target_pointer_size() && - !ctx.options().rust_features().repr_align - { - None + let check_struct_align = if compile_time { + quote! { + [#align_of_err][#align_of_expr - #align]; + } } else { - Some(quote! { - assert_eq!(#align_of_expr, - #align, - concat!("Alignment of ", stringify!(#canonical_ident))); - - }) + quote! { + assert_eq!(#align_of_expr, #align, #align_of_err); + } }; let should_skip_field_offset_checks = is_opaque; @@ -2369,30 +2631,40 @@ impl CodeGenerator for CompInfo { } else { self.fields() .iter() - .filter_map(|field| match *field { - Field::DataMember(ref f) if f.name().is_some() => Some(f), - _ => None, - }) - .flat_map(|field| { - let name = field.name().unwrap(); + .filter_map(|field| { + let Field::DataMember(field) = field else { return None }; + let name = field.name()?; field.offset().map(|offset| { let field_offset = offset / 8; let field_name = ctx.rust_ident(name); - quote! { - assert_eq!( - unsafe { - ::#prefix::ptr::addr_of!((*ptr).#field_name) as usize - ptr as usize - }, - #field_offset, - concat!("Offset of field: ", stringify!(#canonical_ident), "::", stringify!(#field_name)) - ); + let offset_of_err = format!("Offset of field: {canonical_ident}::{field_name}"); + if compile_time { + quote! { + [#offset_of_err][ + ::#prefix::mem::offset_of!(#canonical_ident, #field_name) - #field_offset + ]; + } + } else { + quote! { + assert_eq!( + unsafe { + ::#prefix::ptr::addr_of!((*ptr).#field_name) as usize - ptr as usize + }, + #field_offset, + #offset_of_err + ); + } } }) }) .collect() }; - let uninit_decl = if !check_field_offset.is_empty() { + let uninit_decl = if check_field_offset.is_empty() || + compile_time + { + None + } else { // FIXME: When MSRV >= 1.59.0, we can use // > const PTR: *const #canonical_ident = ::#prefix::mem::MaybeUninit::uninit().as_ptr(); Some(quote! { @@ -2402,35 +2674,42 @@ impl CodeGenerator for CompInfo { const UNINIT: ::#prefix::mem::MaybeUninit<#canonical_ident> = ::#prefix::mem::MaybeUninit::uninit(); let ptr = UNINIT.as_ptr(); }) - } else { - None }; - let item = quote! { - #[test] - fn #fn_name() { - #uninit_decl - assert_eq!(#size_of_expr, - #size, - concat!("Size of: ", stringify!(#canonical_ident))); - #check_struct_align - #( #check_field_offset )* - } - }; - result.push(item); + if compile_time { + result.push(quote! { + #[allow(clippy::unnecessary_operation, clippy::identity_op)] + const _: () = { + [#size_of_err][#size_of_expr - #size]; + #check_struct_align + #( #check_field_offset )* + }; + }); + } else { + result.push(quote! { + #[test] + fn #fn_name() { + #uninit_decl + assert_eq!(#size_of_expr, #size, #size_of_err); + #check_struct_align + #( #check_field_offset )* + } + }); + } } } let mut method_names = Default::default(); if ctx.options().codegen_config.methods() { for method in self.methods() { - assert!(method.kind() != MethodKind::Constructor); + assert_ne!(method.kind(), MethodKind::Constructor); method.codegen_method( ctx, &mut methods, &mut method_names, result, self, + discovered_id, ); } } @@ -2449,6 +2728,7 @@ impl CodeGenerator for CompInfo { &mut method_names, result, self, + discovered_id, ); } } @@ -2462,6 +2742,7 @@ impl CodeGenerator for CompInfo { &mut method_names, result, self, + discovered_id, ); } } @@ -2470,17 +2751,27 @@ impl CodeGenerator for CompInfo { // NB: We can't use to_rust_ty here since for opaque types this tries to // use the specialization knowledge to generate a blob field. let ty_for_impl = quote! { - #canonical_ident #generics + #canonical_ident #impl_generics_params }; if needs_clone_impl { result.push(quote! { - impl #generics Clone for #ty_for_impl { + impl #impl_generics_labels Clone for #ty_for_impl { fn clone(&self) -> Self { *self } } }); } + if needs_flexarray_impl { + result.push(self.generate_flexarray( + ctx, + &canonical_ident, + flex_inner_ty.as_ref(), + &generic_param_names, + &impl_generics_labels, + )); + } + if needs_default_impl { let prefix = ctx.trait_prefix(); let body = if ctx.options().rust_features().maybe_uninit { @@ -2502,10 +2793,10 @@ impl CodeGenerator for CompInfo { }; // Note we use `ptr::write_bytes()` instead of `mem::zeroed()` because the latter does // not necessarily ensure padding bytes are zeroed. Some C libraries are sensitive to - // non-zero padding bytes, especially when forwards/backwards compatability is + // non-zero padding bytes, especially when forwards/backwards compatibility is // involved. result.push(quote! { - impl #generics Default for #ty_for_impl { + impl #impl_generics_labels Default for #ty_for_impl { fn default() -> Self { #body } @@ -2524,7 +2815,7 @@ impl CodeGenerator for CompInfo { let prefix = ctx.trait_prefix(); result.push(quote! { - impl #generics ::#prefix::fmt::Debug for #ty_for_impl { + impl #impl_generics_labels ::#prefix::fmt::Debug for #ty_for_impl { #impl_ } }); @@ -2537,30 +2828,166 @@ impl CodeGenerator for CompInfo { item, &ty_for_impl, ) { - let partialeq_bounds = if !generic_param_names.is_empty() { + let partialeq_bounds = if generic_param_names.is_empty() { + quote! {} + } else { let bounds = generic_param_names.iter().map(|t| { quote! { #t: PartialEq } }); quote! { where #( #bounds ),* } - } else { - quote! {} }; let prefix = ctx.trait_prefix(); result.push(quote! { - impl #generics ::#prefix::cmp::PartialEq for #ty_for_impl #partialeq_bounds { + impl #impl_generics_labels ::#prefix::cmp::PartialEq for #ty_for_impl #partialeq_bounds { #impl_ } }); } - } + } + + if !methods.is_empty() { + result.push(quote! { + impl #impl_generics_labels #ty_for_impl { + #( #methods )* + } + }); + } + } +} + +impl CompInfo { + fn generate_flexarray( + &self, + ctx: &BindgenContext, + canonical_ident: &Ident, + flex_inner_ty: Option<&proc_macro2::TokenStream>, + generic_param_names: &[Ident], + impl_generics_labels: &proc_macro2::TokenStream, + ) -> proc_macro2::TokenStream { + let prefix = ctx.trait_prefix(); + + let flex_array = flex_inner_ty.as_ref().map(|ty| quote! { [ #ty ] }); + + let dst_ty_for_impl = quote! { + #canonical_ident < #( #generic_param_names , )* #flex_array > + + }; + let sized_ty_for_impl = quote! { + #canonical_ident < #( #generic_param_names , )* [ #flex_inner_ty; 0 ] > + }; + + let layout = if ctx.options().rust_features().layout_for_ptr { + quote! { + pub fn layout(len: usize) -> ::#prefix::alloc::Layout { + // SAFETY: Null pointers are OK if we don't deref them + unsafe { + let p: *const Self = ::#prefix::ptr::from_raw_parts(::#prefix::ptr::null::<()>(), len); + ::#prefix::alloc::Layout::for_value_raw(p) + } + } + } + } else { + quote!() + }; + + let (from_ptr_dst, from_ptr_sized) = if ctx + .options() + .rust_features() + .ptr_metadata + { + let flex_ref_inner = ctx.wrap_unsafe_ops(quote! { + Self::flex_ptr(self, len) + }); + let flex_ref_mut_inner = ctx.wrap_unsafe_ops(quote! { + Self::flex_ptr_mut(self, len).assume_init() + }); + let flex_ptr_inner = ctx.wrap_unsafe_ops(quote! { + &*::#prefix::ptr::from_raw_parts(ptr as *const (), len) + }); + let flex_ptr_mut_inner = ctx.wrap_unsafe_ops(quote! { + // Initialize reference without ever exposing it, as its possibly uninitialized + let mut uninit = ::#prefix::mem::MaybeUninit::<&mut #dst_ty_for_impl>::uninit(); + (uninit.as_mut_ptr() as *mut *mut #dst_ty_for_impl) + .write(::#prefix::ptr::from_raw_parts_mut(ptr as *mut (), len)); + + uninit + }); + + ( + quote! { + #[inline] + pub fn fixed(&self) -> (& #sized_ty_for_impl, usize) { + unsafe { + let (ptr, len) = (self as *const Self).to_raw_parts(); + (&*(ptr as *const #sized_ty_for_impl), len) + } + } + + #[inline] + pub fn fixed_mut(&mut self) -> (&mut #sized_ty_for_impl, usize) { + unsafe { + let (ptr, len) = (self as *mut Self).to_raw_parts(); + (&mut *(ptr as *mut #sized_ty_for_impl), len) + } + } + }, + quote! { + /// Convert a sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + pub unsafe fn flex_ref(&self, len: usize) -> &#dst_ty_for_impl { + // SAFETY: Reference is always valid as pointer. Caller is guaranteeing `len`. + #flex_ref_inner + } + + /// Convert a mutable sized prefix to an unsized structure with the given length. + /// + /// SAFETY: Underlying storage is initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ref_mut(&mut self, len: usize) -> &mut #dst_ty_for_impl { + // SAFETY: Reference is always valid as pointer. Caller is guaranteeing `len`. + #flex_ref_mut_inner + } + + /// Construct DST variant from a pointer and a size. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage is fully initialized up to at least `len` elements. + #[inline] + pub unsafe fn flex_ptr<'unbounded>(ptr: *const Self, len: usize) -> &'unbounded #dst_ty_for_impl { + #flex_ptr_inner + } + + /// Construct mutable DST variant from a pointer and a + /// size. The returned `&mut` reference is initialized + /// pointing to memory referenced by `ptr`, but there's + /// no requirement that that memory be initialized. + /// + /// NOTE: lifetime of returned reference is not tied to any underlying storage. + /// SAFETY: `ptr` is valid. Underlying storage has space for at least `len` elements. + #[inline] + pub unsafe fn flex_ptr_mut<'unbounded>( + ptr: *mut Self, + len: usize, + ) -> ::#prefix::mem::MaybeUninit<&'unbounded mut #dst_ty_for_impl> { + #flex_ptr_mut_inner + } + }, + ) + } else { + (quote!(), quote!()) + }; + + quote! { + impl #impl_generics_labels #dst_ty_for_impl { + #layout + #from_ptr_dst + } - if !methods.is_empty() { - result.push(quote! { - impl #generics #ty_for_impl { - #( #methods )* - } - }); + impl #impl_generics_labels #sized_ty_for_impl { + #from_ptr_sized + } } } } @@ -2573,12 +3000,13 @@ impl Method { method_names: &mut HashSet, result: &mut CodegenResult<'_>, _parent: &CompInfo, + parent_id: DiscoveredItemId, ) { assert!({ let cc = &ctx.options().codegen_config; match self.kind() { MethodKind::Constructor => cc.constructors(), - MethodKind::Destructor => cc.destructors(), + MethodKind::Destructor | MethodKind::VirtualDestructor { .. } => cc.destructors(), MethodKind::Static | MethodKind::Normal | @@ -2593,15 +3021,13 @@ impl Method { // First of all, output the actual function. let function_item = ctx.resolve_item(self.signature()); + let id = DiscoveredItemId::new(function_item.id().as_usize()); if !function_item.process_before_codegen(ctx, result) { return; } let function = function_item.expect_function(); let times_seen = function.codegen(ctx, result, function_item); - let times_seen = match times_seen { - Some(seen) => seen, - None => return, - }; + let Some(times_seen) = times_seen else { return }; let signature_item = ctx.resolve_item(function.signature()); let mut name = match self.kind() { MethodKind::Constructor => "new".into(), @@ -2609,9 +3035,10 @@ impl Method { _ => function.name().to_owned(), }; - let signature = match *signature_item.expect_type().kind() { - TypeKind::Function(ref sig) => sig, - _ => panic!("How in the world?"), + let TypeKind::Function(ref signature) = + *signature_item.expect_type().kind() + else { + panic!("How in the world?") }; let supported_abi = signature.abi(ctx, Some(&*name)).is_ok(); @@ -2630,7 +3057,7 @@ impl Method { let mut new_name; while { - new_name = format!("{}{}", name, count); + new_name = format!("{name}{count}"); method_names.contains(&new_name) } { count += 1; @@ -2641,9 +3068,19 @@ impl Method { method_names.insert(name.clone()); + ctx.options().for_each_callback(|cb| { + cb.new_item_found( + id, + DiscoveredItem::Method { + parent: parent_id, + final_name: name.clone(), + }, + ); + }); + let mut function_name = function_item.canonical_name(ctx); if times_seen > 0 { - write!(&mut function_name, "{}", times_seen).unwrap(); + write!(&mut function_name, "{times_seen}").unwrap(); } let function_name = ctx.rust_ident(function_name); let mut args = utils::fnsig_arguments(ctx, signature); @@ -2701,7 +3138,7 @@ impl Method { exprs[0] = quote! { self }; - }; + } let call = quote! { #function_name (#( #exprs ),* ) @@ -2718,16 +3155,14 @@ impl Method { quote! { __bindgen_tmp } - }) + }); } let block = ctx.wrap_unsafe_ops(quote! ( #( #stmts );*)); let mut attrs = vec![attributes::inline()]; - if signature.must_use() && - ctx.options().rust_features().must_use_function - { + if signature.must_use() { attrs.push(attributes::must_use()); } @@ -2742,11 +3177,11 @@ impl Method { } /// A helper type that represents different enum variations. -#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] pub enum EnumVariation { /// The code for this enum will use a Rust enum. Note that creating this in unsafe code /// (including FFI) with an invalid value will invoke undefined behaviour, whether or not - /// its marked as non_exhaustive. + /// its marked as `#[non_exhaustive]`. Rust { /// Indicates whether the generated struct should be `#[non_exhaustive]` non_exhaustive: bool, @@ -2759,26 +3194,21 @@ pub enum EnumVariation { is_global: bool, }, /// The code for this enum will use consts + #[default] Consts, /// The code for this enum will use a module containing consts ModuleConsts, } impl EnumVariation { - fn is_rust(&self) -> bool { - matches!(*self, EnumVariation::Rust { .. }) + fn is_rust(self) -> bool { + matches!(self, EnumVariation::Rust { .. }) } /// Both the `Const` and `ModuleConsts` variants will cause this to return /// true. - fn is_const(&self) -> bool { - matches!(*self, EnumVariation::Consts | EnumVariation::ModuleConsts) - } -} - -impl Default for EnumVariation { - fn default() -> EnumVariation { - EnumVariation::Consts + fn is_const(self) -> bool { + matches!(self, EnumVariation::Consts | EnumVariation::ModuleConsts) } } @@ -2811,7 +3241,7 @@ impl fmt::Display for EnumVariation { } } -impl std::str::FromStr for EnumVariation { +impl FromStr for EnumVariation { type Err = std::io::Error; /// Create a `EnumVariation` from a string. @@ -2849,216 +3279,211 @@ impl std::str::FromStr for EnumVariation { } } +struct EnumBuilder { + /// Type identifier of the enum. + /// + /// This is the base name, i.e. for `ModuleConst` enums, this does not include the module name. + enum_type: Ident, + /// Attributes applying to the enum type + attrs: Vec, + /// The representation of the enum, e.g. `u32`. + repr: syn::Type, + /// The enum kind we are generating + kind: EnumBuilderKind, + /// A list of all variants this enum has. + enum_variants: Vec, +} + /// A helper type to construct different enum variations. -enum EnumBuilder<'a> { +enum EnumBuilderKind { Rust { - attrs: Vec, - ident: Ident, - tokens: proc_macro2::TokenStream, - emitted_any_variants: bool, + non_exhaustive: bool, }, NewType { - canonical_name: &'a str, - tokens: proc_macro2::TokenStream, is_bitfield: bool, is_global: bool, + /// if the enum is named or not. + is_anonymous: bool, }, Consts { - variants: Vec, + needs_typedef: bool, }, ModuleConsts { - module_name: &'a str, - module_items: Vec, + module_name: Ident, }, } -impl<'a> EnumBuilder<'a> { +impl EnumBuilder { /// Returns true if the builder is for a rustified enum. fn is_rust_enum(&self) -> bool { - matches!(*self, EnumBuilder::Rust { .. }) + matches!(self.kind, EnumBuilderKind::Rust { .. }) } /// Create a new enum given an item builder, a canonical name, a name for /// the representation, and which variation it should be generated as. fn new( - name: &'a str, - mut attrs: Vec, - repr: syn::Type, + name: &str, + attrs: Vec, + repr: &syn::Type, enum_variation: EnumVariation, has_typedef: bool, + enum_is_anonymous: bool, ) -> Self { let ident = Ident::new(name, Span::call_site()); + // For most variants this is the same + let mut enum_ty = ident.clone(); - match enum_variation { + let kind = match enum_variation { EnumVariation::NewType { is_bitfield, is_global, - } => EnumBuilder::NewType { - canonical_name: name, - tokens: quote! { - #( #attrs )* - pub struct #ident (pub #repr); - }, + } => EnumBuilderKind::NewType { is_bitfield, is_global, + is_anonymous: enum_is_anonymous, }, - EnumVariation::Rust { .. } => { - // `repr` is guaranteed to be Rustified in Enum::codegen - attrs.insert(0, quote! { #[repr( #repr )] }); - let tokens = quote!(); - EnumBuilder::Rust { - attrs, - ident, - tokens, - emitted_any_variants: false, - } + EnumVariation::Rust { non_exhaustive } => { + EnumBuilderKind::Rust { non_exhaustive } } - EnumVariation::Consts => { - let mut variants = Vec::new(); - - if !has_typedef { - variants.push(quote! { - #( #attrs )* - pub type #ident = #repr; - }); - } - - EnumBuilder::Consts { variants } - } + EnumVariation::Consts => EnumBuilderKind::Consts { + needs_typedef: !has_typedef, + }, EnumVariation::ModuleConsts => { - let ident = Ident::new( + enum_ty = Ident::new( CONSTIFIED_ENUM_MODULE_REPR_NAME, Span::call_site(), ); - let type_definition = quote! { - #( #attrs )* - pub type #ident = #repr; - }; - EnumBuilder::ModuleConsts { - module_name: name, - module_items: vec![type_definition], + EnumBuilderKind::ModuleConsts { + module_name: ident.clone(), } } + }; + EnumBuilder { + enum_type: enum_ty, + attrs, + repr: repr.clone(), + kind, + enum_variants: vec![], } } /// Add a variant to this enum. fn with_variant( - self, + mut self, ctx: &BindgenContext, variant: &EnumVariant, + variant_doc: proc_macro2::TokenStream, mangling_prefix: Option<&str>, - rust_ty: syn::Type, - result: &mut CodegenResult<'_>, + rust_ty: &syn::Type, is_ty_named: bool, ) -> Self { let variant_name = ctx.rust_mangle(variant.name()); let is_rust_enum = self.is_rust_enum(); let expr = match variant.val() { EnumVariantValue::Boolean(v) if is_rust_enum => { - helpers::ast_ty::uint_expr(v as u64) + helpers::ast_ty::uint_expr(u64::from(v)) } EnumVariantValue::Boolean(v) => quote!(#v), EnumVariantValue::Signed(v) => helpers::ast_ty::int_expr(v), EnumVariantValue::Unsigned(v) => helpers::ast_ty::uint_expr(v), }; - let mut doc = quote! {}; - if ctx.options().generate_comments { - if let Some(raw_comment) = variant.comment() { - let comment = ctx.options().process_comment(raw_comment); - doc = attributes::doc(comment); - } - } - - match self { - EnumBuilder::Rust { - attrs, - ident, - tokens, - emitted_any_variants: _, - } => { + match self.kind { + EnumBuilderKind::Rust { .. } => { let name = ctx.rust_ident(variant_name); - EnumBuilder::Rust { - attrs, - ident, - tokens: quote! { - #tokens - #doc - #name = #expr, - }, - emitted_any_variants: true, - } + self.enum_variants.push(EnumVariantInfo { + variant_name: name, + variant_doc, + value: expr, + }); + self } - EnumBuilder::NewType { - canonical_name, - is_global, - .. - } => { - if ctx.options().rust_features().associated_const && - is_ty_named && - !is_global - { - let enum_ident = ctx.rust_ident(canonical_name); - let variant_ident = ctx.rust_ident(variant_name); - - result.push(quote! { - impl #enum_ident { - #doc - pub const #variant_ident : #rust_ty = #rust_ty ( #expr ); - } - }); + EnumBuilderKind::NewType { is_global, .. } => { + let variant_ident = if is_ty_named && !is_global { + ctx.rust_ident(variant_name) } else { - let ident = ctx.rust_ident(match mangling_prefix { + ctx.rust_ident(match mangling_prefix { Some(prefix) => { - Cow::Owned(format!("{}_{}", prefix, variant_name)) + Cow::Owned(format!("{prefix}_{variant_name}")) } None => variant_name, - }); - result.push(quote! { - #doc - pub const #ident : #rust_ty = #rust_ty ( #expr ); - }); - } + }) + }; + self.enum_variants.push(EnumVariantInfo { + variant_name: variant_ident, + variant_doc, + value: quote! { #rust_ty ( #expr )}, + }); self } - EnumBuilder::Consts { .. } => { + EnumBuilderKind::Consts { .. } => { let constant_name = match mangling_prefix { Some(prefix) => { - Cow::Owned(format!("{}_{}", prefix, variant_name)) + Cow::Owned(format!("{prefix}_{variant_name}")) } None => variant_name, }; let ident = ctx.rust_ident(constant_name); - result.push(quote! { - #doc - pub const #ident : #rust_ty = #expr ; + self.enum_variants.push(EnumVariantInfo { + variant_name: ident, + variant_doc, + value: quote! { #expr }, }); self } - EnumBuilder::ModuleConsts { - module_name, - mut module_items, - } => { + EnumBuilderKind::ModuleConsts { .. } => { let name = ctx.rust_ident(variant_name); - let ty = ctx.rust_ident(CONSTIFIED_ENUM_MODULE_REPR_NAME); - module_items.push(quote! { - #doc - pub const #name : #ty = #expr ; + self.enum_variants.push(EnumVariantInfo { + variant_name: name, + variant_doc, + value: quote! { #expr }, }); + self + } + } + } + + fn newtype_bitfield_impl( + prefix: &Ident, + rust_ty: &syn::Type, + ) -> proc_macro2::TokenStream { + let rust_ty_name = &rust_ty; + quote! { + impl ::#prefix::ops::BitOr<#rust_ty> for #rust_ty { + type Output = Self; + + #[inline] + fn bitor(self, other: Self) -> Self { + #rust_ty_name(self.0 | other.0) + } + } + impl ::#prefix::ops::BitOrAssign for #rust_ty { + #[inline] + fn bitor_assign(&mut self, rhs: #rust_ty) { + self.0 |= rhs.0; + } + } + impl ::#prefix::ops::BitAnd<#rust_ty> for #rust_ty { + type Output = Self; - EnumBuilder::ModuleConsts { - module_name, - module_items, + #[inline] + fn bitand(self, other: Self) -> Self { + #rust_ty_name(self.0 & other.0) + } + } + impl ::#prefix::ops::BitAndAssign for #rust_ty { + #[inline] + fn bitand_assign(&mut self, rhs: #rust_ty) { + self.0 &= rhs.0; } } } @@ -3067,95 +3492,142 @@ impl<'a> EnumBuilder<'a> { fn build( self, ctx: &BindgenContext, - rust_ty: syn::Type, - result: &mut CodegenResult<'_>, + rust_ty: &syn::Type, ) -> proc_macro2::TokenStream { - match self { - EnumBuilder::Rust { - attrs, - ident, - tokens, - emitted_any_variants, - .. - } => { - let variants = if !emitted_any_variants { - quote!(__bindgen_cannot_repr_c_on_empty_enum = 0) - } else { - tokens - }; + let enum_ident = self.enum_type; + + // 1. Construct a list of the enum variants + let variants = match self.kind { + EnumBuilderKind::Rust { .. } => { + let mut variants = vec![]; + + for v in self.enum_variants { + let variant_doc = &v.variant_doc; + let variant_ident = &v.variant_name; + let variant_value = &v.value; + + variants.push(quote! { + #variant_doc + #variant_ident = #variant_value, + }); + } + + if variants.is_empty() { + variants.push( + quote! {__bindgen_cannot_repr_c_on_empty_enum = 0,}, + ); + } + variants + } + EnumBuilderKind::NewType { .. } => { + let mut variants = vec![]; + + for v in self.enum_variants { + let variant_doc = &v.variant_doc; + let variant_ident = &v.variant_name; + let variant_value = &v.value; + + variants.push(quote! { + #variant_doc + pub const #variant_ident: #enum_ident = #variant_value; + }); + } + variants + } + EnumBuilderKind::Consts { .. } | + EnumBuilderKind::ModuleConsts { .. } => { + let mut variants = vec![]; + + for v in self.enum_variants { + let variant_doc = &v.variant_doc; + let variant_ident = &v.variant_name; + let variant_value = &v.value; + + variants.push(quote! { + #variant_doc + pub const #variant_ident: #enum_ident = #variant_value; + }); + } + variants + } + }; + let attrs = self.attrs; + let enum_repr = &self.repr; + + // 2. Generate the enum representation + match self.kind { + EnumBuilderKind::Rust { non_exhaustive } => { + let non_exhaustive_opt = + non_exhaustive.then(attributes::non_exhaustive); quote! { + // Note: repr is on top of attrs to keep the test expectations diff small. + // a future commit could move it further down. + #[repr(#enum_repr)] + #non_exhaustive_opt #( #attrs )* - pub enum #ident { - #variants + pub enum #enum_ident { + #( #variants )* } } } - EnumBuilder::NewType { - canonical_name, - tokens, + EnumBuilderKind::NewType { is_bitfield, - .. + is_global, + is_anonymous, } => { - if !is_bitfield { - return tokens; - } - - let rust_ty_name = ctx.rust_ident_raw(canonical_name); - let prefix = ctx.trait_prefix(); - - result.push(quote! { - impl ::#prefix::ops::BitOr<#rust_ty> for #rust_ty { - type Output = Self; - - #[inline] - fn bitor(self, other: Self) -> Self { - #rust_ty_name(self.0 | other.0) - } + // There doesn't seem to be a technical reason why we generate + // anon enum variants as global constants. + // We keep this behavior to avoid breaking changes in the bindings. + let impl_variants = if is_anonymous || is_global { + quote! { + #( #variants )* } - }); - - result.push(quote! { - impl ::#prefix::ops::BitOrAssign for #rust_ty { - #[inline] - fn bitor_assign(&mut self, rhs: #rust_ty) { - self.0 |= rhs.0; + } else { + quote! { + impl #enum_ident { + #( #variants )* } } - }); + }; - result.push(quote! { - impl ::#prefix::ops::BitAnd<#rust_ty> for #rust_ty { - type Output = Self; + let prefix = ctx.trait_prefix(); + let bitfield_impl_opt = is_bitfield + .then(|| Self::newtype_bitfield_impl(&prefix, rust_ty)); - #[inline] - fn bitand(self, other: Self) -> Self { - #rust_ty_name(self.0 & other.0) - } - } - }); + quote! { + // Previously variant impls where before the enum definition. + // lets keep this as is for now, to reduce the diff in generated bindings. + #impl_variants - result.push(quote! { - impl ::#prefix::ops::BitAndAssign for #rust_ty { - #[inline] - fn bitand_assign(&mut self, rhs: #rust_ty) { - self.0 &= rhs.0; - } + #bitfield_impl_opt + + #[repr(transparent)] + #( #attrs )* + pub struct #enum_ident (pub #enum_repr); + } + } + EnumBuilderKind::Consts { needs_typedef } => { + let typedef_opt = needs_typedef.then(|| { + quote! { + #( #attrs )* + pub type #enum_ident = #enum_repr; } }); + quote! { + #( #variants )* - tokens + #typedef_opt + } } - EnumBuilder::Consts { variants, .. } => quote! { #( #variants )* }, - EnumBuilder::ModuleConsts { - module_items, - module_name, - .. - } => { - let ident = ctx.rust_ident(module_name); + EnumBuilderKind::ModuleConsts { module_name, .. } => { quote! { - pub mod #ident { - #( #module_items )* + // todo: Probably some attributes, e.g. `cfg` should apply to the `mod`. + pub mod #module_name { + #( #attrs )* + pub type #enum_ident = #enum_repr; + + #( #variants )* } } } @@ -3173,7 +3645,7 @@ impl CodeGenerator for Enum { result: &mut CodegenResult<'_>, item: &Item, ) { - debug!("::codegen: item = {:?}", item); + debug!("::codegen: item = {item:?}"); debug_assert!(item.is_enabled_for_codegen(ctx)); let name = item.canonical_name(ctx); @@ -3198,18 +3670,17 @@ impl CodeGenerator for Enum { // * the representation couldn't be determined from the C source // * it was explicitly requested as a bindgen option - let kind = match repr { - Some(repr) => match *repr.canonical_type(ctx).kind() { + let kind = if let Some(repr) = repr { + match *repr.canonical_type(ctx).kind() { TypeKind::Int(int_kind) => int_kind, _ => panic!("Unexpected type as enum repr"), - }, - None => { - warn!( - "Guessing type of enum! Forward declarations of enums \ - shouldn't be legal!" - ); - IntKind::Int } + } else { + warn!( + "Guessing type of enum! Forward declarations of enums \ + shouldn't be legal!" + ); + IntKind::Int }; let signed = kind.is_signed(); @@ -3229,8 +3700,7 @@ impl CodeGenerator for Enum { (false, 8) => IntKind::U64, _ => { warn!( - "invalid enum decl: signed: {}, size: {}", - signed, size + "invalid enum decl: signed: {signed}, size: {size}" ); IntKind::I32 } @@ -3244,31 +3714,8 @@ impl CodeGenerator for Enum { let mut attrs = vec![]; - // TODO(emilio): Delegate this to the builders? - match variation { - EnumVariation::Rust { non_exhaustive } => { - if non_exhaustive && - ctx.options().rust_features().non_exhaustive - { - attrs.push(attributes::non_exhaustive()); - } else if non_exhaustive && - !ctx.options().rust_features().non_exhaustive - { - panic!("The rust target you're using doesn't seem to support non_exhaustive enums"); - } - } - EnumVariation::NewType { .. } => { - if ctx.options().rust_features.repr_transparent { - attrs.push(attributes::repr("transparent")); - } else { - attrs.push(attributes::repr("C")); - } - } - _ => {} - }; - if let Some(comment) = item.comment(ctx) { - attrs.push(attributes::doc(comment)); + attrs.push(attributes::doc(&comment)); } if item.must_use(ctx) { @@ -3288,7 +3735,7 @@ impl CodeGenerator for Enum { DerivableTraits::EQ, ); let mut derives: Vec<_> = derives.into(); - for derive in item.annotations().derives().iter() { + for derive in item.annotations().derives() { if !derives.contains(&derive.as_str()) { derives.push(derive); } @@ -3305,6 +3752,23 @@ impl CodeGenerator for Enum { // In most cases this will be a no-op, since custom_derives will be empty. derives.extend(custom_derives.iter().map(|s| s.as_str())); + attrs.extend( + item.annotations() + .attributes() + .iter() + .map(|s| s.parse().unwrap()), + ); + + // The custom attribute callback may return a list of attributes; + // add them to the end of the list. + let custom_attributes = ctx.options().all_callbacks(|cb| { + cb.add_attributes(&AttributeInfo { + name: &name, + kind: DeriveTypeKind::Enum, + }) + }); + attrs.extend(custom_attributes.iter().map(|s| s.parse().unwrap())); + attrs.push(attributes::derives(&derives)); } @@ -3318,17 +3782,17 @@ impl CodeGenerator for Enum { // value. variant_name: &Ident, referenced_name: &Ident, - enum_rust_ty: syn::Type, + enum_rust_ty: &syn::Type, result: &mut CodegenResult<'_>, ) { let constant_name = if enum_.name().is_some() { if ctx.options().prepend_enum_name { - format!("{}_{}", enum_canonical_name, variant_name) + format!("{enum_canonical_name}_{variant_name}") } else { - format!("{}", variant_name) + format!("{variant_name}") } } else { - format!("{}", variant_name) + format!("{variant_name}") }; let constant_name = ctx.rust_ident(constant_name); @@ -3341,8 +3805,23 @@ impl CodeGenerator for Enum { let repr = repr.to_rust_ty_or_opaque(ctx, item); let has_typedef = ctx.is_enum_typedef_combo(item.id()); - let mut builder = - EnumBuilder::new(&name, attrs, repr, variation, has_typedef); + ctx.options().for_each_callback(|cb| { + cb.new_item_found( + DiscoveredItemId::new(item.id().as_usize()), + DiscoveredItem::Enum { + final_name: name.to_string(), + }, + ); + }); + + let mut builder = EnumBuilder::new( + &name, + attrs, + &repr, + variation, + has_typedef, + enum_ty.name().is_none(), + ); // A map where we keep a value -> variant relation. let mut seen_values = HashMap::<_, Ident>::default(); @@ -3384,28 +3863,33 @@ impl CodeGenerator for Enum { continue; } + let mut variant_doc = quote! {}; + if ctx.options().generate_comments { + if let Some(raw_comment) = variant.comment() { + let processed_comment = + ctx.options().process_comment(raw_comment); + variant_doc = attributes::doc(&processed_comment); + } + } + match seen_values.entry(variant.val()) { Entry::Occupied(ref entry) => { if variation.is_rust() { let variant_name = ctx.rust_mangle(variant.name()); - let mangled_name = - if is_toplevel || enum_ty.name().is_some() { - variant_name - } else { - let parent_name = - parent_canonical_name.as_ref().unwrap(); + let mangled_name = if is_toplevel || + enum_ty.name().is_some() + { + variant_name + } else { + let parent_name = + parent_canonical_name.as_ref().unwrap(); - Cow::Owned(format!( - "{}_{}", - parent_name, variant_name - )) - }; + Cow::Owned(format!("{parent_name}_{variant_name}")) + }; let existing_variant_name = entry.get(); // Use associated constants for named enums. - if enum_ty.name().is_some() && - ctx.options().rust_features().associated_const - { + if enum_ty.name().is_some() { let enum_canonical_name = &ident; let variant_name = ctx.rust_ident_raw(&*mangled_name); @@ -3422,7 +3906,7 @@ impl CodeGenerator for Enum { &ident, &Ident::new(&mangled_name, Span::call_site()), existing_variant_name, - enum_rust_ty.clone(), + &enum_rust_ty, result, ); } @@ -3430,9 +3914,9 @@ impl CodeGenerator for Enum { builder = builder.with_variant( ctx, variant, + variant_doc, constant_mangling_prefix, - enum_rust_ty.clone(), - result, + &enum_rust_ty, enum_ty.name().is_some(), ); } @@ -3441,9 +3925,9 @@ impl CodeGenerator for Enum { builder = builder.with_variant( ctx, variant, + variant_doc, constant_mangling_prefix, - enum_rust_ty.clone(), - result, + &enum_rust_ty, enum_ty.name().is_some(), ); @@ -3462,7 +3946,7 @@ impl CodeGenerator for Enum { parent_canonical_name.as_ref().unwrap(); Ident::new( - &format!("{}_{}", parent_name, variant_name), + &format!("{parent_name}_{variant_name}"), Span::call_site(), ) }; @@ -3473,7 +3957,7 @@ impl CodeGenerator for Enum { &ident, &mangled_name, &variant_name, - enum_rust_ty.clone(), + &enum_rust_ty, result, ); } @@ -3483,17 +3967,24 @@ impl CodeGenerator for Enum { } } - let item = builder.build(ctx, enum_rust_ty, result); + let item = builder.build(ctx, &enum_rust_ty); result.push(item); } } +struct EnumVariantInfo { + variant_name: Ident, + variant_doc: proc_macro2::TokenStream, + value: proc_macro2::TokenStream, +} + /// Enum for the default type of macro constants. -#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] pub enum MacroTypeVariation { /// Use i32 or i64 Signed, /// Use u32 or u64 + #[default] Unsigned, } @@ -3507,13 +3998,7 @@ impl fmt::Display for MacroTypeVariation { } } -impl Default for MacroTypeVariation { - fn default() -> MacroTypeVariation { - MacroTypeVariation::Unsigned - } -} - -impl std::str::FromStr for MacroTypeVariation { +impl FromStr for MacroTypeVariation { type Err = std::io::Error; /// Create a `MacroTypeVariation` from a string. @@ -3533,13 +4018,14 @@ impl std::str::FromStr for MacroTypeVariation { } /// Enum for how aliases should be translated. -#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] pub enum AliasVariation { /// Convert to regular Rust alias + #[default] TypeAlias, /// Create a new type by wrapping the old type in a struct and using #[repr(transparent)] NewType, - /// Same as NewStruct but also impl Deref to be able to use the methods of the wrapped type + /// Same as `NewType` but also impl Deref to be able to use the methods of the wrapped type NewTypeDeref, } @@ -3555,13 +4041,7 @@ impl fmt::Display for AliasVariation { } } -impl Default for AliasVariation { - fn default() -> AliasVariation { - AliasVariation::TypeAlias - } -} - -impl std::str::FromStr for AliasVariation { +impl FromStr for AliasVariation { type Err = std::io::Error; /// Create an `AliasVariation` from a string. @@ -3610,7 +4090,7 @@ impl Default for NonCopyUnionStyle { } } -impl std::str::FromStr for NonCopyUnionStyle { +impl FromStr for NonCopyUnionStyle { type Err = std::io::Error; fn from_str(s: &str) -> Result { @@ -3650,7 +4130,7 @@ pub(crate) trait TryToOpaque { extra: &Self::Extra, ) -> error::Result { self.try_get_layout(ctx, extra) - .map(|layout| helpers::blob(ctx, layout)) + .map(|layout| helpers::blob(ctx, layout, true)) } } @@ -3676,7 +4156,7 @@ pub(crate) trait ToOpaque: TryToOpaque { extra: &Self::Extra, ) -> syn::Type { let layout = self.get_layout(ctx, extra); - helpers::blob(ctx, layout) + helpers::blob(ctx, layout, true) } } @@ -3727,9 +4207,9 @@ where ) -> error::Result { self.try_to_rust_ty(ctx, extra).or_else(|_| { if let Ok(layout) = self.try_get_layout(ctx, extra) { - Ok(helpers::blob(ctx, layout)) + Ok(helpers::blob(ctx, layout, true)) } else { - Err(error::Error::NoLayoutForOpaqueBlob) + Err(Error::NoLayoutForOpaqueBlob) } }) } @@ -3744,11 +4224,11 @@ where /// ### Fallible vs. Infallible Conversions to Rust Types /// /// When should one use this infallible `ToRustTyOrOpaque` trait versus the -/// fallible `TryTo{RustTy, Opaque, RustTyOrOpaque}` triats? All fallible trait +/// fallible `TryTo{RustTy, Opaque, RustTyOrOpaque}` traits? All fallible trait /// implementations that need to convert another thing into a Rust type or /// opaque blob in a nested manner should also use fallible trait methods and /// propagate failure up the stack. Only infallible functions and methods like -/// CodeGenerator implementations should use the infallible +/// `CodeGenerator` implementations should use the infallible /// `ToRustTyOrOpaque`. The further out we push error recovery, the more likely /// we are to get a usable `Layout` even if we can't generate an equivalent Rust /// type for a C++ construct. @@ -3840,7 +4320,7 @@ impl TryToOpaque for Type { ctx: &BindgenContext, _: &Item, ) -> error::Result { - self.layout(ctx).ok_or(error::Error::NoLayoutForOpaqueBlob) + self.layout(ctx).ok_or(Error::NoLayoutForOpaqueBlob) } } @@ -3982,7 +4462,7 @@ impl TryToRustTy for Type { Ok(syn::parse_quote! { #name }) } ref u @ TypeKind::UnresolvedTypeRef(..) => { - unreachable!("Should have been resolved after parsing {:?}!", u) + unreachable!("Should have been resolved after parsing {u:?}!") } } } @@ -3998,7 +4478,7 @@ impl TryToOpaque for TemplateInstantiation { ) -> error::Result { item.expect_type() .layout(ctx) - .ok_or(error::Error::NoLayoutForOpaqueBlob) + .ok_or(Error::NoLayoutForOpaqueBlob) } } @@ -4011,7 +4491,7 @@ impl TryToRustTy for TemplateInstantiation { item: &Item, ) -> error::Result { if self.is_opaque(ctx, item) { - return Err(error::Error::InstantiationOfOpaqueType); + return Err(Error::InstantiationOfOpaqueType); } let def = self @@ -4033,7 +4513,7 @@ impl TryToRustTy for TemplateInstantiation { // template specialization, and we've hit an instantiation of // that partial specialization. extra_assert!(def.is_opaque(ctx, &())); - return Err(error::Error::InstantiationOfOpaqueType); + return Err(Error::InstantiationOfOpaqueType); } // TODO: If the definition type is a template class/struct @@ -4085,7 +4565,7 @@ impl TryToRustTy for FunctionSig { syn::parse_quote! { unsafe extern #abi fn ( #( #arguments ),* ) #ret }, ), Err(err) => { - if matches!(err, error::Error::UnsupportedAbi(_)) { + if matches!(err, Error::UnsupportedAbi(_)) { unsupported_abi_diagnostic( self.name(), self.is_variadic(), @@ -4114,16 +4594,16 @@ impl CodeGenerator for Function { result: &mut CodegenResult<'_>, item: &Item, ) -> Self::Return { - debug!("::codegen: item = {:?}", item); + debug!("::codegen: item = {item:?}"); debug_assert!(item.is_enabled_for_codegen(ctx)); + let id = DiscoveredItemId::new(item.id().as_usize()); let is_internal = matches!(self.linkage(), Linkage::Internal); let signature_item = ctx.resolve_item(self.signature()); let signature = signature_item.kind().expect_type().canonical_type(ctx); - let signature = match *signature.kind() { - TypeKind::Function(ref sig) => sig, - _ => panic!("Signature kind is not a Function: {:?}", signature), + let TypeKind::Function(ref signature) = *signature.kind() else { + panic!("Signature kind is not a Function: {signature:?}") }; if is_internal { @@ -4141,18 +4621,24 @@ impl CodeGenerator for Function { } } - // Pure virtual methods have no actual symbol, so we can't generate - // something meaningful for them. - let is_dynamic_function = match self.kind() { - FunctionKind::Method(ref method_kind) - if method_kind.is_pure_virtual() => - { - return None; + let is_pure_virtual = match self.kind() { + FunctionKind::Method(ref method_kind) => { + method_kind.is_pure_virtual() } + FunctionKind::Function => false, + }; + if is_pure_virtual && !ctx.options().generate_pure_virtual_functions { + // Pure virtual methods have no actual symbol, so we can't generate + // something meaningful for them. Downstream code postprocessors + // might want to find out about them. + return None; + } + + let is_dynamic_function = match self.kind() { FunctionKind::Function => { ctx.options().dynamic_library_name.is_some() } - _ => false, + FunctionKind::Method(_) => false, }; // Similar to static member variables in a class template, we can't @@ -4180,7 +4666,7 @@ impl CodeGenerator for Function { let mut attributes = vec![]; - if ctx.options().rust_features().must_use_function { + if true { let must_use = signature.must_use() || { let ret_ty = signature .return_type() @@ -4196,12 +4682,12 @@ impl CodeGenerator for Function { } if let Some(comment) = item.comment(ctx) { - attributes.push(attributes::doc(comment)); + attributes.push(attributes::doc(&comment)); } let abi = match signature.abi(ctx, Some(name)) { Err(err) => { - if matches!(err, error::Error::UnsupportedAbi(_)) { + if matches!(err, Error::UnsupportedAbi(_)) { unsupported_abi_diagnostic( name, signature.is_variadic(), @@ -4215,8 +4701,7 @@ impl CodeGenerator for Function { } Ok(ClangAbi::Unknown(unknown_abi)) => { panic!( - "Invalid or unknown abi {:?} for function {:?} ({:?})", - unknown_abi, canonical_name, self + "Invalid or unknown abi {unknown_abi:?} for function {canonical_name:?} ({self:?})" ); } Ok(abi) => abi, @@ -4226,24 +4711,30 @@ impl CodeGenerator for Function { // suffix. let times_seen = result.overload_number(&canonical_name); if times_seen > 0 { - write!(&mut canonical_name, "{}", times_seen).unwrap(); + write!(&mut canonical_name, "{times_seen}").unwrap(); } + ctx.options().for_each_callback(|cb| { + cb.new_item_found( + id, + DiscoveredItem::Function { + final_name: canonical_name.to_string(), + }, + ); + }); - let mut has_link_name_attr = false; - if let Some(link_name) = self.link_name() { - attributes.push(attributes::link_name::(link_name)); - has_link_name_attr = true; - } else { - let link_name = mangled_name.unwrap_or(name); - if !is_dynamic_function && - !utils::names_will_be_identical_after_mangling( - &canonical_name, - link_name, - Some(abi), - ) - { + let link_name_attr = self.link_name().or_else(|| { + let mangled_name = mangled_name.unwrap_or(name); + (!utils::names_will_be_identical_after_mangling( + &canonical_name, + mangled_name, + Some(abi), + )) + .then_some(mangled_name) + }); + + if let Some(link_name) = link_name_attr { + if !is_dynamic_function { attributes.push(attributes::link_name::(link_name)); - has_link_name_attr = true; } } @@ -4255,8 +4746,9 @@ impl CodeGenerator for Function { quote! { #[link(wasm_import_module = #name)] } }); - let should_wrap = - is_internal && ctx.options().wrap_static_fns && !has_link_name_attr; + let should_wrap = is_internal && + ctx.options().wrap_static_fns && + link_name_attr.is_none(); if should_wrap { let name = canonical_name.clone() + ctx.wrap_static_fns_suffix(); @@ -4298,9 +4790,16 @@ impl CodeGenerator for Function { let ret = utils::fnsig_return_ty(ctx, signature); let ident = ctx.rust_ident(ident); + + let safety = ctx + .options() + .rust_features + .unsafe_extern_blocks + .then(|| quote!(unsafe)); + let tokens = quote! { #wasm_link_attribute - extern #abi { + #safety extern #abi { #(#attributes)* pub fn #ident ( #( #args ),* ) #ret; } @@ -4315,19 +4814,22 @@ impl CodeGenerator for Function { // If we're doing dynamic binding generation, add to the dynamic items. if is_dynamic_function { + let ident_str = ident.to_string(); + let symbol = link_name_attr.unwrap_or(&ident_str); let args_identifiers = utils::fnsig_argument_identifiers(ctx, signature); let ret_ty = utils::fnsig_return_ty(ctx, signature); - result.dynamic_items().push( - ident, + result.dynamic_items().push_func( + &ident, + symbol, abi, signature.is_variadic(), ctx.options().dynamic_link_require_all, - args, - args_identifiers, - ret, - ret_ty, - attributes, + &args, + &args_identifiers, + &ret, + &ret_ty, + &attributes, ctx, ); } else { @@ -4343,13 +4845,11 @@ fn unsupported_abi_diagnostic( variadic: bool, location: Option<&crate::clang::SourceLocation>, ctx: &BindgenContext, - error: &error::Error, + error: &Error, ) { warn!( - "Skipping {}function `{}` because the {}", + "Skipping {}function `{fn_name}` because the {error}", if variadic { "variadic " } else { "" }, - fn_name, - error ); #[cfg(feature = "experimental")] @@ -4359,16 +4859,14 @@ fn unsupported_abi_diagnostic( let mut diag = Diagnostic::default(); diag.with_title( format!( - "Skipping {}function `{}` because the {}", + "Skipping {}function `{fn_name}` because the {error}", if variadic { "variadic " } else { "" }, - fn_name, - error ), - Level::Warn, + Level::Warning, ) .add_annotation( "No code will be generated for this function.", - Level::Warn, + Level::Warning, ) .add_annotation( format!( @@ -4392,7 +4890,7 @@ fn unsupported_abi_diagnostic( } } - diag.display() + diag.display(); } } @@ -4402,8 +4900,7 @@ fn variadic_fn_diagnostic( _ctx: &BindgenContext, ) { warn!( - "Cannot generate wrapper for the static variadic function `{}`.", - fn_name, + "Cannot generate wrapper for the static variadic function `{fn_name}`." ); #[cfg(feature = "experimental")] @@ -4412,7 +4909,7 @@ fn variadic_fn_diagnostic( let mut diag = Diagnostic::default(); - diag.with_title(format!("Cannot generate wrapper for the static function `{}`.", fn_name), Level::Warn) + diag.with_title(format!("Cannot generate wrapper for the static function `{fn_name}`."), Level::Warning) .add_annotation("The `--wrap-static-fns` feature does not support variadic functions.", Level::Note) .add_annotation("No code will be generated for this function.", Level::Note); @@ -4430,7 +4927,7 @@ fn variadic_fn_diagnostic( } } - diag.display() + diag.display(); } } @@ -4445,7 +4942,7 @@ fn objc_method_codegen( // This would ideally resolve the method into an Item, and use // Item::process_before_codegen; however, ObjC methods are not currently // made into function items. - let name = format!("{}::{}{}", rust_class_name, prefix, method.rust_name()); + let name = format!("{rust_class_name}::{prefix}{}", method.rust_name()); if ctx.options().blocklisted_items.matches(name) { return; } @@ -4482,8 +4979,7 @@ fn objc_method_codegen( ctx.wrap_unsafe_ops(body) }; - let method_name = - ctx.rust_ident(format!("{}{}", prefix, method.rust_name())); + let method_name = ctx.rust_ident(format!("{prefix}{}", method.rust_name())); methods.push(quote! { unsafe fn #method_name #sig where ::Target: objc::Message + Sized { @@ -4584,7 +5080,7 @@ impl CodeGenerator for ObjCInterface { }; result.push(struct_block); let mut protocol_set: HashSet = Default::default(); - for protocol_id in self.conforms_to.iter() { + for protocol_id in &self.conforms_to { protocol_set.insert(*protocol_id); let protocol_name = ctx.rust_ident( ctx.resolve_type(protocol_id.expect_type_id(ctx)) @@ -4606,9 +5102,8 @@ impl CodeGenerator for ObjCInterface { .expect_type() .kind(); - let parent = match parent { - TypeKind::ObjCInterface(ref parent) => parent, - _ => break, + let TypeKind::ObjCInterface(parent) = parent else { + break; }; parent_class = parent.parent_class; @@ -4629,7 +5124,7 @@ impl CodeGenerator for ObjCInterface { } }; result.push(impl_trait); - for protocol_id in parent.conforms_to.iter() { + for protocol_id in &parent.conforms_to { if protocol_set.insert(*protocol_id) { let protocol_name = ctx.rust_ident( ctx.resolve_type(protocol_id.expect_type_id(ctx)) @@ -4656,8 +5151,7 @@ impl CodeGenerator for ObjCInterface { result.push(from_block); let error_msg = format!( - "This {} cannot be downcasted to {}", - parent_struct_name, child_struct_name + "This {parent_struct_name} cannot be downcasted to {child_struct_name}" ); let try_into_block = quote! { impl std::convert::TryFrom<#parent_struct> for #class_name { @@ -4716,7 +5210,7 @@ pub(crate) fn codegen( let codegen_items = context.codegen_items(); for (id, item) in context.items() { if codegen_items.contains(&id) { - println!("ir: {:?} = {:#?}", id, item); + println!("ir: {id:?} = {item:#?}"); } } } @@ -4724,10 +5218,9 @@ pub(crate) fn codegen( if let Some(path) = context.options().emit_ir_graphviz.as_ref() { match dot::write_dot_file(context, path) { Ok(()) => info!( - "Your dot file was generated successfully into: {}", - path + "Your dot file was generated successfully into: {path}" ), - Err(e) => warn!("{}", e), + Err(e) => warn!("{e}"), } } @@ -4737,7 +5230,7 @@ pub(crate) fn codegen( "Your depfile was generated successfully into: {}", spec.depfile_path.display() ), - Err(e) => warn!("{}", e), + Err(e) => warn!("{e}"), } } @@ -4750,7 +5243,7 @@ pub(crate) fn codegen( if let Some(ref lib_name) = context.options().dynamic_library_name { let lib_ident = context.rust_ident(lib_name); let dynamic_items_tokens = - result.dynamic_items().get_tokens(lib_ident, context); + result.dynamic_items().get_tokens(&lib_ident, context); result.push(dynamic_items_tokens); } @@ -4764,6 +5257,7 @@ pub(crate) fn codegen( } pub(crate) mod utils { + use super::helpers::BITFIELD_UNIT; use super::serialize::CSerialize; use super::{error, CodegenError, CodegenResult, ToRustTyOrOpaque}; use crate::ir::context::BindgenContext; @@ -4786,14 +5280,10 @@ pub(crate) mod utils { return Ok(()); } - let path = context - .options() - .wrap_static_fns_path - .as_ref() - .map(PathBuf::from) - .unwrap_or_else(|| { - std::env::temp_dir().join("bindgen").join("extern") - }); + let path = context.options().wrap_static_fns_path.as_ref().map_or_else( + || std::env::temp_dir().join("bindgen").join("extern"), + PathBuf::from, + ); let dir = path.parent().unwrap(); @@ -4814,7 +5304,7 @@ pub(crate) mod utils { if !context.options().input_headers.is_empty() { for header in &context.options().input_headers { - writeln!(code, "#include \"{}\"", header)?; + writeln!(code, "#include \"{header}\"")?; } writeln!(code)?; @@ -4822,7 +5312,7 @@ pub(crate) mod utils { if !context.options().input_header_contents.is_empty() { for (name, contents) in &context.options().input_header_contents { - writeln!(code, "// {}\n{}", name, contents)?; + writeln!(code, "// {name}\n{contents}")?; } writeln!(code)?; @@ -4862,10 +5352,10 @@ pub(crate) mod utils { } match ty.kind() { TypeKind::Alias(type_id_alias) => { - type_id = *type_id_alias + type_id = *type_id_alias; } TypeKind::ResolvedTypeRef(type_id_typedef) => { - type_id = *type_id_typedef + type_id = *type_id_typedef; } _ => break, } @@ -4900,8 +5390,19 @@ pub(crate) mod utils { ctx: &BindgenContext, result: &mut Vec, ) { - let bitfield_unit_src = include_str!("./bitfield_unit.rs"); - let bitfield_unit_src = if ctx.options().rust_features().min_const_fn { + if ctx.options().blocklisted_items.matches(BITFIELD_UNIT) || + ctx.options().blocklisted_types.matches(BITFIELD_UNIT) + { + return; + } + + let bitfield_unit_src = if ctx.options().rust_features().raw_ref_macros + { + include_str!("./bitfield_unit_raw_ref_macros.rs") + } else { + include_str!("./bitfield_unit.rs") + }; + let bitfield_unit_src = if true { Cow::Borrowed(bitfield_unit_src) } else { Cow::Owned(bitfield_unit_src.replace("const fn ", "fn ")) @@ -4967,7 +5468,7 @@ pub(crate) mod utils { // If the target supports `const fn`, declare eligible functions // as `const fn` else just `fn`. - let const_fn = if ctx.options().rust_features().min_const_fn { + let const_fn = if true { quote! { const fn } } else { quote! { fn } @@ -5079,7 +5580,7 @@ pub(crate) mod utils { // If the target supports `const fn`, declare eligible functions // as `const fn` else just `fn`. - let const_fn = if ctx.options().rust_features().min_const_fn { + let const_fn = if true { quote! { const fn } } else { quote! { fn } @@ -5178,6 +5679,25 @@ pub(crate) mod utils { result.extend(old_items); } + pub(crate) fn prepend_opaque_array_type( + result: &mut Vec, + ) { + let ty = quote! { + /// If Bindgen could only determine the size and alignment of a + /// type, it is represented like this. + #[derive(PartialEq, Copy, Clone, Debug, Hash)] + #[repr(C)] + pub struct __BindgenOpaqueArray(pub [T; N]); + impl Default for __BindgenOpaqueArray { + fn default() -> Self { + Self([::default(); N]) + } + } + }; + + result.insert(0, ty); + } + pub(crate) fn build_path( item: &Item, ctx: &BindgenContext, @@ -5263,7 +5783,7 @@ pub(crate) mod utils { pub(crate) fn fnsig_argument_type( ctx: &BindgenContext, - ty: &TypeId, + ty: TypeId, ) -> syn::Type { use super::ToPtr; @@ -5285,7 +5805,8 @@ pub(crate) mod utils { } else { t.to_rust_ty_or_opaque(ctx, &()) }; - stream.to_ptr(ctx.resolve_type(t).is_const()) + stream + .to_ptr(ctx.resolve_type(t).is_const() || arg_ty.is_const()) } TypeKind::Pointer(inner) => { let inner = ctx.resolve_item(inner); @@ -5305,7 +5826,7 @@ pub(crate) mod utils { pub(crate) fn fnsig_arguments_iter< 'a, - I: Iterator, crate::ir::context::TypeId)>, + I: Iterator, TypeId)>, >( ctx: &BindgenContext, args_iter: I, @@ -5314,14 +5835,13 @@ pub(crate) mod utils { let mut unnamed_arguments = 0; let mut args = args_iter .map(|(name, ty)| { - let arg_ty = fnsig_argument_type(ctx, ty); + let arg_ty = fnsig_argument_type(ctx, *ty); - let arg_name = match *name { - Some(ref name) => ctx.rust_mangle(name).into_owned(), - None => { - unnamed_arguments += 1; - format!("arg{}", unnamed_arguments) - } + let arg_name = if let Some(ref name) = *name { + ctx.rust_mangle(name).into_owned() + } else { + unnamed_arguments += 1; + format!("arg{unnamed_arguments}") }; assert!(!arg_name.is_empty()); @@ -5334,7 +5854,7 @@ pub(crate) mod utils { .collect::>(); if is_variadic { - args.push(quote! { ... }) + args.push(quote! { ... }); } args @@ -5360,12 +5880,11 @@ pub(crate) mod utils { .argument_types() .iter() .map(|&(ref name, _ty)| { - let arg_name = match *name { - Some(ref name) => ctx.rust_mangle(name).into_owned(), - None => { - unnamed_arguments += 1; - format!("arg{}", unnamed_arguments) - } + let arg_name = if let Some(ref name) = *name { + ctx.rust_mangle(name).into_owned() + } else { + unnamed_arguments += 1; + format!("arg{unnamed_arguments}") }; assert!(!arg_name.is_empty()); @@ -5442,7 +5961,7 @@ pub(crate) mod utils { // Check that the mangled name contains the canonical name after the // prefix - if &mangled_name[1..canonical_name.len() + 1] != canonical_name { + if &mangled_name[1..=canonical_name.len()] != canonical_name { return false; } diff --git a/bindgen/codegen/postprocessing/merge_extern_blocks.rs b/bindgen/codegen/postprocessing/merge_extern_blocks.rs index 10fa0ec80b..e0f6a34baa 100644 --- a/bindgen/codegen/postprocessing/merge_extern_blocks.rs +++ b/bindgen/codegen/postprocessing/merge_extern_blocks.rs @@ -4,7 +4,7 @@ use syn::{ }; pub(super) fn merge_extern_blocks(file: &mut File) { - Visitor.visit_file_mut(file) + Visitor.visit_file_mut(file); } struct Visitor; @@ -12,14 +12,14 @@ struct Visitor; impl VisitMut for Visitor { fn visit_file_mut(&mut self, file: &mut File) { visit_items(&mut file.items); - visit_file_mut(self, file) + visit_file_mut(self, file); } fn visit_item_mod_mut(&mut self, item_mod: &mut ItemMod) { if let Some((_, ref mut items)) = item_mod.content { visit_items(items); } - visit_item_mod_mut(self, item_mod) + visit_item_mod_mut(self, item_mod); } } diff --git a/bindgen/codegen/postprocessing/sort_semantically.rs b/bindgen/codegen/postprocessing/sort_semantically.rs index be94ce69c5..e9bb5dc308 100644 --- a/bindgen/codegen/postprocessing/sort_semantically.rs +++ b/bindgen/codegen/postprocessing/sort_semantically.rs @@ -4,7 +4,7 @@ use syn::{ }; pub(super) fn sort_semantically(file: &mut File) { - Visitor.visit_file_mut(file) + Visitor.visit_file_mut(file); } struct Visitor; @@ -12,14 +12,14 @@ struct Visitor; impl VisitMut for Visitor { fn visit_file_mut(&mut self, file: &mut File) { visit_items(&mut file.items); - visit_file_mut(self, file) + visit_file_mut(self, file); } fn visit_item_mod_mut(&mut self, item_mod: &mut ItemMod) { if let Some((_, ref mut items)) = item_mod.content { visit_items(items); } - visit_item_mod_mut(self, item_mod) + visit_item_mod_mut(self, item_mod); } } diff --git a/bindgen/codegen/serialize.rs b/bindgen/codegen/serialize.rs index 7f00f809f4..9af48aa8ff 100644 --- a/bindgen/codegen/serialize.rs +++ b/bindgen/codegen/serialize.rs @@ -14,8 +14,7 @@ use super::{CodegenError, WrapAsVariadic}; fn get_loc(item: &Item) -> String { item.location() - .map(|x| x.to_string()) - .unwrap_or_else(|| "unknown".to_owned()) + .map_or_else(|| "unknown".to_owned(), |x| x.to_string()) } pub(super) trait CSerialize<'a> { @@ -45,7 +44,7 @@ impl<'a> CSerialize<'a> for Item { func.serialize(ctx, (self, extra), stack, writer) } kind => Err(CodegenError::Serialize { - msg: format!("Cannot serialize item kind {:?}", kind), + msg: format!("Cannot serialize item kind {kind:?}"), loc: get_loc(self), }), } @@ -72,9 +71,10 @@ impl<'a> CSerialize<'a> for Function { }); } - let signature = match ctx.resolve_type(self.signature()).kind() { - TypeKind::Function(signature) => signature, - _ => unreachable!(), + let TypeKind::Function(signature) = + ctx.resolve_type(self.signature()).kind() + else { + unreachable!() }; assert!(!signature.is_variadic()); @@ -102,7 +102,7 @@ impl<'a> CSerialize<'a> for Function { } else { Some(( opt_name.unwrap_or_else(|| { - let name = format!("arg_{}", count); + let name = format!("arg_{count}"); count += 1; name }), @@ -114,7 +114,7 @@ impl<'a> CSerialize<'a> for Function { }; // The name used for the wrapper self. - let wrap_name = format!("{}{}", name, ctx.wrap_static_fns_suffix()); + let wrap_name = format!("{name}{}", ctx.wrap_static_fns_suffix()); // The function's return type let (ret_item, ret_ty) = { @@ -131,15 +131,15 @@ impl<'a> CSerialize<'a> for Function { const INDENT: &str = " "; // Write `wrap_name(args`. - write!(writer, " {}(", wrap_name)?; + write!(writer, " {wrap_name}(")?; serialize_args(&args, ctx, writer)?; if wrap_as_variadic.is_none() { // Write `) { name(` if the function returns void and `) { return name(` if it does not. if ret_ty.is_void() { - write!(writer, ") {{ {}(", name)?; + write!(writer, ") {{ {name}(")?; } else { - write!(writer, ") {{ return {}(", name)?; + write!(writer, ") {{ return {name}(")?; } } else { // Write `, ...) {` @@ -165,7 +165,7 @@ impl<'a> CSerialize<'a> for Function { if !ret_ty.is_void() { write!(writer, "ret = ")?; } - write!(writer, "{}(", name)?; + write!(writer, "{name}(")?; } // Get the arguments names and insert at the right place if necessary `ap` @@ -179,7 +179,7 @@ impl<'a> CSerialize<'a> for Function { // Write `arg_names);`. serialize_sep(", ", args.iter(), ctx, writer, |name, _, buf| { - write!(buf, "{}", name).map_err(From::from) + write!(buf, "{name}").map_err(From::from) })?; #[rustfmt::skip] write!(writer, ");{}", if wrap_as_variadic.is_none() { " " } else { "\n" })?; @@ -198,7 +198,7 @@ impl<'a> CSerialize<'a> for Function { } } -impl<'a> CSerialize<'a> for TypeId { +impl CSerialize<'_> for TypeId { type Extra = (); fn serialize( @@ -228,13 +228,13 @@ impl<'a> CSerialize<'a> for Type { if self.is_const() { write!(writer, "const ")?; } - write!(writer, "void")? + write!(writer, "void")?; } TypeKind::NullPtr => { if self.is_const() { write!(writer, "const ")?; } - write!(writer, "nullptr_t")? + write!(writer, "nullptr_t")?; } TypeKind::Int(int_kind) => { if self.is_const() { @@ -257,8 +257,7 @@ impl<'a> CSerialize<'a> for Type { int_kind => { return Err(CodegenError::Serialize { msg: format!( - "Cannot serialize integer kind {:?}", - int_kind + "Cannot serialize integer kind {int_kind:?}" ), loc: get_loc(item), }) @@ -286,7 +285,7 @@ impl<'a> CSerialize<'a> for Type { FloatKind::Float => write!(writer, "float complex")?, FloatKind::Double => write!(writer, "double complex")?, FloatKind::LongDouble => { - write!(writer, "long double complex")? + write!(writer, "long double complex")?; } FloatKind::Float128 => write!(writer, "__complex128")?, } @@ -294,9 +293,9 @@ impl<'a> CSerialize<'a> for Type { TypeKind::Alias(type_id) => { if let Some(name) = self.name() { if self.is_const() { - write!(writer, "const {}", name)?; + write!(writer, "const {name}")?; } else { - write!(writer, "{}", name)?; + write!(writer, "{name}")?; } } else { type_id.serialize(ctx, (), stack, writer)?; @@ -304,7 +303,7 @@ impl<'a> CSerialize<'a> for Type { } TypeKind::Array(type_id, length) => { type_id.serialize(ctx, (), stack, writer)?; - write!(writer, " [{}]", length)? + write!(writer, " [{length}]")?; } TypeKind::Function(signature) => { if self.is_const() { @@ -320,7 +319,7 @@ impl<'a> CSerialize<'a> for Type { write!(writer, " (")?; while let Some(item) = stack.pop() { - write!(writer, "{}", item)?; + write!(writer, "{item}")?; } write!(writer, ")")?; @@ -342,14 +341,14 @@ impl<'a> CSerialize<'a> for Type { type_id.serialize(ctx, (), &mut stack, buf) }, )?; - write!(writer, ")")? + write!(writer, ")")?; } } TypeKind::ResolvedTypeRef(type_id) => { if self.is_const() { write!(writer, "const ")?; } - type_id.serialize(ctx, (), stack, writer)? + type_id.serialize(ctx, (), stack, writer)?; } TypeKind::Pointer(type_id) => { if self.is_const() { @@ -357,7 +356,7 @@ impl<'a> CSerialize<'a> for Type { } else { stack.push("*".to_owned()); } - type_id.serialize(ctx, (), stack, writer)? + type_id.serialize(ctx, (), stack, writer)?; } TypeKind::Comp(comp_info) => { if self.is_const() { @@ -367,9 +366,9 @@ impl<'a> CSerialize<'a> for Type { let name = item.canonical_name(ctx); match comp_info.kind() { - CompKind::Struct => write!(writer, "struct {}", name)?, - CompKind::Union => write!(writer, "union {}", name)?, - }; + CompKind::Struct => write!(writer, "struct {name}")?, + CompKind::Union => write!(writer, "union {name}")?, + } } TypeKind::Enum(_enum_ty) => { if self.is_const() { @@ -377,20 +376,20 @@ impl<'a> CSerialize<'a> for Type { } let name = item.canonical_name(ctx); - write!(writer, "enum {}", name)?; + write!(writer, "enum {name}")?; } ty => { return Err(CodegenError::Serialize { - msg: format!("Cannot serialize type kind {:?}", ty), + msg: format!("Cannot serialize type kind {ty:?}"), loc: get_loc(item), }) } - }; + } if !stack.is_empty() { write!(writer, " ")?; while let Some(item) = stack.pop() { - write!(writer, "{}", item)?; + write!(writer, "{item}")?; } } diff --git a/bindgen/codegen/struct_layout.rs b/bindgen/codegen/struct_layout.rs index f4596a1992..0d2e6a05c5 100644 --- a/bindgen/codegen/struct_layout.rs +++ b/bindgen/codegen/struct_layout.rs @@ -7,7 +7,7 @@ use crate::ir::context::BindgenContext; use crate::ir::layout::Layout; use crate::ir::ty::{Type, TypeKind}; use crate::FieldVisibilityKind; -use proc_macro2::{self, Ident, Span}; +use proc_macro2::{Ident, Span}; use std::cmp; const MAX_GUARANTEED_ALIGN: usize = 8; @@ -28,6 +28,7 @@ pub(crate) struct StructLayoutTracker<'a> { max_field_align: usize, last_field_was_bitfield: bool, visibility: FieldVisibilityKind, + last_field_was_flexible_array: bool, } /// Returns a size aligned to a given value. @@ -110,6 +111,7 @@ impl<'a> StructLayoutTracker<'a> { latest_field_layout: None, max_field_align: 0, last_field_was_bitfield: false, + last_field_was_flexible_array: false, } } @@ -121,6 +123,10 @@ impl<'a> StructLayoutTracker<'a> { self.is_rust_union } + pub(crate) fn saw_flexible_array(&mut self) { + self.last_field_was_flexible_array = true; + } + pub(crate) fn saw_vtable(&mut self) { debug!("saw vtable for {}", self.name); @@ -142,7 +148,7 @@ impl<'a> StructLayoutTracker<'a> { } pub(crate) fn saw_bitfield_unit(&mut self, layout: Layout) { - debug!("saw bitfield unit for {}: {:?}", self.name, layout); + debug!("saw bitfield unit for {}: {layout:?}", self.name); self.align_to_latest_field(layout); @@ -242,12 +248,9 @@ impl<'a> StructLayoutTracker<'a> { ); debug!( - "align field {} to {}/{} with {} padding bytes {:?}", - field_name, + "align field {field_name} to {}/{} with {padding_bytes} padding bytes {field_layout:?}", self.latest_offset, field_offset.unwrap_or(0) / 8, - padding_bytes, - field_layout ); let padding_align = if force_padding { @@ -263,15 +266,19 @@ impl<'a> StructLayoutTracker<'a> { } }; - self.latest_offset += field_layout.size; + if is_union { + self.latest_offset = + cmp::max(self.latest_offset, field_layout.size); + } else { + self.latest_offset += field_layout.size; + } self.latest_field_layout = Some(field_layout); self.max_field_align = cmp::max(self.max_field_align, field_layout.align); self.last_field_was_bitfield = false; debug!( - "Offset: {}: {} -> {}", - field_name, + "Offset: {field_name}: {} -> {}", self.latest_offset - field_layout.size, self.latest_offset ); @@ -295,14 +302,18 @@ impl<'a> StructLayoutTracker<'a> { return None; } + // Also doesn't make sense for structs with flexible array members + if self.last_field_was_flexible_array { + return None; + } + if self.latest_offset == comp_layout.size { // This struct does not contain tail padding. return None; } trace!( - "need a tail padding field for {}: offset {} -> size {}", - comp_name, + "need a tail padding field for {comp_name}: offset {} -> size {}", self.latest_offset, comp_layout.size ); @@ -314,10 +325,7 @@ impl<'a> StructLayoutTracker<'a> { &mut self, layout: Layout, ) -> Option { - debug!( - "pad_struct:\n\tself = {:#?}\n\tlayout = {:#?}", - self, layout - ); + debug!("pad_struct:\n\tself = {self:#?}\n\tlayout = {layout:#?}"); if layout.size < self.latest_offset { warn!( @@ -333,7 +341,7 @@ impl<'a> StructLayoutTracker<'a> { return None; } - let repr_align = self.ctx.options().rust_features().repr_align; + let repr_align = true; // We always pad to get to the correct size if the struct is one of // those we can't align properly. @@ -357,7 +365,7 @@ impl<'a> StructLayoutTracker<'a> { Layout::new(padding_bytes, layout.align) }; - debug!("pad bytes to struct {}, {:?}", self.name, layout); + debug!("pad bytes to struct {}, {layout:?}", self.name); Some(self.padding_field(layout)) } else { @@ -366,7 +374,7 @@ impl<'a> StructLayoutTracker<'a> { } pub(crate) fn requires_explicit_align(&self, layout: Layout) -> bool { - let repr_align = self.ctx.options().rust_features().repr_align; + let repr_align = true; // Always force explicit repr(align) for stuff more than 16-byte aligned // to work-around https://github.com/rust-lang/rust/issues/54341. @@ -390,13 +398,13 @@ impl<'a> StructLayoutTracker<'a> { } fn padding_field(&mut self, layout: Layout) -> proc_macro2::TokenStream { - let ty = helpers::blob(self.ctx, layout); + let ty = helpers::blob(self.ctx, layout, false); let padding_count = self.padding_count; self.padding_count += 1; let padding_field_name = Ident::new( - &format!("__bindgen_padding_{}", padding_count), + &format!("__bindgen_padding_{padding_count}"), Span::call_site(), ); @@ -411,23 +419,22 @@ impl<'a> StructLayoutTracker<'a> { /// Returns whether the new field is known to merge with a bitfield. /// - /// This is just to avoid doing the same check also in pad_field. + /// This is just to avoid doing the same check also in `pad_field`. fn align_to_latest_field(&mut self, new_field_layout: Layout) -> bool { if self.is_packed { // Skip to align fields when packed. return false; } - let layout = match self.latest_field_layout { - Some(l) => l, - None => return false, + let Some(layout) = self.latest_field_layout else { + return false; }; // If it was, we may or may not need to align, depending on what the // current field alignment and the bitfield size and alignment are. debug!( - "align_to_bitfield? {}: {:?} {:?}", - self.last_field_was_bitfield, layout, new_field_layout + "align_to_bitfield? {}: {layout:?} {new_field_layout:?}", + self.last_field_was_bitfield, ); // Avoid divide-by-zero errors if align is 0. diff --git a/bindgen/deps.rs b/bindgen/deps.rs index be31f92896..3f95ac1e89 100644 --- a/bindgen/deps.rs +++ b/bindgen/deps.rs @@ -18,7 +18,7 @@ impl DepfileSpec { let mut buf = format!("{}:", escape(&self.output_module)); for file in deps { - buf = format!("{} {}", buf, escape(file)); + buf = format!("{buf} {}", escape(file)); } buf } diff --git a/bindgen/diagnostics.rs b/bindgen/diagnostics.rs index f765afe970..f22402ac0e 100644 --- a/bindgen/diagnostics.rs +++ b/bindgen/diagnostics.rs @@ -6,33 +6,9 @@ use std::fmt::Write; use std::io::{self, BufRead, BufReader}; use std::{borrow::Cow, fs::File}; -use annotate_snippets::{ - display_list::{DisplayList, FormatOptions}, - snippet::{Annotation, Slice as ExtSlice, Snippet}, -}; - -use annotate_snippets::snippet::AnnotationType; - -#[derive(Clone, Copy, Debug)] -pub(crate) enum Level { - Error, - Warn, - Info, - Note, - Help, -} +use annotate_snippets::{Renderer, Snippet}; -impl From for AnnotationType { - fn from(level: Level) -> Self { - match level { - Level::Error => Self::Error, - Level::Warn => Self::Warning, - Level::Info => Self::Info, - Level::Note => Self::Note, - Level::Help => Self::Help, - } - } -} +pub(crate) use annotate_snippets::Level; /// A `bindgen` diagnostic. #[derive(Default)] @@ -78,55 +54,37 @@ impl<'a> Diagnostic<'a> { static INVOKED_BY_BUILD_SCRIPT: bool = std::env::var_os("CARGO_CFG_TARGET_ARCH").is_some(); } - let mut title = None; let mut footer = vec![]; let mut slices = vec![]; - if let Some((msg, level)) = &self.title { - title = Some(Annotation { - id: Some("bindgen"), - label: Some(msg.as_ref()), - annotation_type: (*level).into(), - }) - } + let snippet = if let Some((msg, level)) = &self.title { + (*level).title(msg) + } else { + return; + }; for (msg, level) in &self.footer { - footer.push(Annotation { - id: None, - label: Some(msg.as_ref()), - annotation_type: (*level).into(), - }); + footer.push((*level).title(msg)); } // add additional info that this is generated by bindgen // so as to not confuse with rustc warnings - footer.push(Annotation { - id: None, - label: Some("This diagnostic was generated by bindgen."), - annotation_type: AnnotationType::Info, - }); + footer.push( + Level::Info.title("This diagnostic was generated by bindgen."), + ); for slice in &self.slices { if let Some(source) = &slice.source { - slices.push(ExtSlice { - source: source.as_ref(), - line_start: slice.line.unwrap_or_default(), - origin: slice.filename.as_deref(), - annotations: vec![], - fold: false, - }) + let mut snippet = Snippet::source(source) + .line_start(slice.line.unwrap_or_default()); + if let Some(origin) = &slice.filename { + snippet = snippet.origin(origin); + } + slices.push(snippet); } } - let snippet = Snippet { - title, - footer, - slices, - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - let dl = DisplayList::from(snippet); + let renderer = Renderer::styled(); + let dl = renderer.render(snippet.snippets(slices).footers(footer)); if INVOKED_BY_BUILD_SCRIPT.with(Clone::clone) { // This is just a hack which hides the `warning:` added by cargo at the beginning of @@ -135,10 +93,10 @@ impl<'a> Diagnostic<'a> { let hide_warning = "\r \r"; let string = dl.to_string(); for line in string.lines() { - println!("cargo:warning={}{}", hide_warning, line); + println!("cargo:warning={hide_warning}{line}"); } } else { - eprintln!("{}\n", dl); + eprintln!("{dl}\n"); } } } @@ -168,8 +126,7 @@ impl<'a> Slice<'a> { line: usize, col: usize, ) -> &mut Self { - write!(name, ":{}:{}", line, col) - .expect("Writing to a string cannot fail"); + write!(name, ":{line}:{col}").expect("Writing to a string cannot fail"); self.filename = Some(name); self.line = Some(line); self diff --git a/bindgen/extra_assertions.rs b/bindgen/extra_assertions.rs index fbddad7825..8526fd42d2 100644 --- a/bindgen/extra_assertions.rs +++ b/bindgen/extra_assertions.rs @@ -2,7 +2,7 @@ //! and/or CI when the `__testing_only_extra_assertions` feature is enabled. /// Simple macro that forwards to assert! when using -/// __testing_only_extra_assertions. +/// `__testing_only_extra_assertions`. macro_rules! extra_assert { ( $cond:expr ) => { if cfg!(feature = "__testing_only_extra_assertions") { diff --git a/bindgen/features.rs b/bindgen/features.rs index e5e2068053..5864b88f42 100644 --- a/bindgen/features.rs +++ b/bindgen/features.rs @@ -4,85 +4,242 @@ #![deny(clippy::missing_docs_in_private_items)] #![allow(deprecated)] -use std::cmp::Ordering; -use std::io; use std::str::FromStr; +use std::{fmt, io}; + +/// Represents the version of the Rust language to target. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[repr(transparent)] +pub struct RustTarget(Version); + +impl RustTarget { + /// Create a new [`RustTarget`] for a stable release of Rust. + pub fn stable(minor: u64, patch: u64) -> Result { + let target = Self(Version::Stable(minor, patch)); + + if target < EARLIEST_STABLE_RUST { + return Err(InvalidRustTarget::TooEarly); + } + + Ok(target) + } + + const fn minor(&self) -> Option { + match self.0 { + Version::Nightly => None, + Version::Stable(minor, _) => Some(minor), + } + } + + const fn is_compatible(&self, other: &Self) -> bool { + match (self.0, other.0) { + (Version::Stable(minor, _), Version::Stable(other_minor, _)) => { + // We ignore the patch version number as they only include backwards compatible bug + // fixes. + minor >= other_minor + } + // Nightly is compatible with everything + (Version::Nightly, _) => true, + // No stable release is compatible with nightly + (Version::Stable { .. }, Version::Nightly) => false, + } + } +} + +impl Default for RustTarget { + fn default() -> Self { + LATEST_STABLE_RUST + } +} + +impl fmt::Display for RustTarget { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + Version::Stable(minor, patch) => write!(f, "1.{minor}.{patch}"), + Version::Nightly => "nightly".fmt(f), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +enum Version { + Stable(u64, u64), + Nightly, +} + +#[derive(Debug, PartialEq, Eq, Hash)] +pub enum InvalidRustTarget { + TooEarly, +} + +impl fmt::Display for InvalidRustTarget { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooEarly => write!(f, "the earliest Rust version supported by bindgen is {EARLIEST_STABLE_RUST}"), + } + } +} + +/// This macro defines the Rust editions supported by bindgen. +macro_rules! define_rust_editions { + ($($variant:ident($value:literal) => $minor:literal,)*) => { + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] + #[doc = "Represents Rust Edition for the generated bindings"] + pub enum RustEdition { + $( + #[doc = concat!("The ", stringify!($value), " edition of Rust.")] + $variant, + )* + } + + impl FromStr for RustEdition { + type Err = InvalidRustEdition; + + fn from_str(s: &str) -> Result { + match s { + $(stringify!($value) => Ok(Self::$variant),)* + _ => Err(InvalidRustEdition(s.to_owned())), + } + } + } + + impl fmt::Display for RustEdition { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + $(Self::$variant => stringify!($value).fmt(f),)* + } + } + } + + impl RustEdition { + pub(crate) const ALL: [Self; [$($value,)*].len()] = [$(Self::$variant,)*]; + + pub(crate) fn is_available(self, target: RustTarget) -> bool { + let Some(minor) = target.minor() else { + return true; + }; + + match self { + $(Self::$variant => $minor <= minor,)* + } + } + } + } +} + +#[derive(Debug)] +pub struct InvalidRustEdition(String); + +impl fmt::Display for InvalidRustEdition { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" is not a valid Rust edition", self.0) + } +} + +impl std::error::Error for InvalidRustEdition {} + +define_rust_editions! { + Edition2018(2018) => 31, + Edition2021(2021) => 56, + Edition2024(2024) => 85, +} + +impl RustTarget { + /// Returns the latest edition supported by this target. + pub(crate) fn latest_edition(self) -> RustEdition { + RustEdition::ALL + .iter() + .rev() + .find(|edition| edition.is_available(self)) + .copied() + .expect("bindgen should always support at least one edition") + } +} + +impl Default for RustEdition { + fn default() -> Self { + RustTarget::default().latest_edition() + } +} /// This macro defines the [`RustTarget`] and [`RustFeatures`] types. macro_rules! define_rust_targets { ( - Nightly => {$($nightly_feature:ident $(: #$issue:literal)?),* $(,)?} $(,)? + Nightly => {$($nightly_feature:ident $(($nightly_edition:literal))|* $(: #$issue:literal)?),* $(,)?} $(,)? $( - $(#[$attrs:meta])* - $variant:ident($minor:literal) => {$($feature:ident $(: #$pull:literal)?),* $(,)?}, + $variant:ident($minor:literal) => {$($feature:ident $(($edition:literal))|* $(: #$pull:literal)?),* $(,)?}, )* $(,)? ) => { - /// Represents the version of the Rust language to target. - /// - /// To support a beta release, use the corresponding stable release. - /// - /// This enum will have more variants added as necessary. - #[allow(non_camel_case_types)] - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] - pub enum RustTarget { - /// Rust Nightly + + impl RustTarget { + /// The nightly version of Rust, which introduces the following features:" + $(#[doc = concat!( + "- [`", stringify!($nightly_feature), "`]", + "(", $("https://github.com/rust-lang/rust/pull/", stringify!($issue),)* ")", + )])* + #[deprecated = "The use of this constant is deprecated, please use `RustTarget::nightly` instead."] + pub const Nightly: Self = Self::nightly(); + + /// The nightly version of Rust, which introduces the following features:" $(#[doc = concat!( "- [`", stringify!($nightly_feature), "`]", "(", $("https://github.com/rust-lang/rust/pull/", stringify!($issue),)* ")", )])* - Nightly, + pub const fn nightly() -> Self { + Self(Version::Nightly) + } + $( - #[doc = concat!("Rust 1.", stringify!($minor))] + #[doc = concat!("Version 1.", stringify!($minor), " of Rust, which introduced the following features:")] $(#[doc = concat!( "- [`", stringify!($feature), "`]", "(", $("https://github.com/rust-lang/rust/pull/", stringify!($pull),)* ")", )])* - $(#[$attrs])* - $variant, + #[deprecated = "The use of this constant is deprecated, please use `RustTarget::stable` instead."] + pub const $variant: Self = Self(Version::Stable($minor, 0)); )* - } - - impl RustTarget { - fn minor(self) -> Option { - match self { - $( Self::$variant => Some($minor),)* - Self::Nightly => None - } - } const fn stable_releases() -> [(Self, u64); [$($minor,)*].len()] { [$((Self::$variant, $minor),)*] } } - #[cfg(feature = "__cli")] - /// Strings of allowed `RustTarget` values - pub const RUST_TARGET_STRINGS: &[&str] = &[$(concat!("1.", stringify!($minor)),)*]; - #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub(crate) struct RustFeatures { $($(pub(crate) $feature: bool,)*)* $(pub(crate) $nightly_feature: bool,)* } - impl From for RustFeatures { - fn from(target: RustTarget) -> Self { - if target == RustTarget::Nightly { - return Self { - $($($feature: true,)*)* - $($nightly_feature: true,)* - }; - } - + impl RustFeatures { + /// Compute the features that must be enabled in a specific Rust target with a specific edition. + pub(crate) fn new(target: RustTarget, edition: RustEdition) -> Self { let mut features = Self { $($($feature: false,)*)* $($nightly_feature: false,)* }; - $(if target >= RustTarget::$variant { - $(features.$feature = true;)* - })* + if target.is_compatible(&RustTarget::nightly()) { + $( + let editions: &[RustEdition] = &[$(stringify!($nightly_edition).parse::().ok().expect("invalid edition"),)*]; + + if editions.is_empty() || editions.contains(&edition) { + features.$nightly_feature = true; + } + )* + } + + $( + if target.is_compatible(&RustTarget::$variant) { + $( + let editions: &[RustEdition] = &[$(stringify!($edition).parse::().ok().expect("invalid edition"),)*]; + + if editions.is_empty() || editions.contains(&edition) { + features.$feature = true; + } + )* + } + )* features } @@ -95,43 +252,34 @@ macro_rules! define_rust_targets { // not stable. define_rust_targets! { Nightly => { - vectorcall_abi, + vectorcall_abi: #124485, + ptr_metadata: #81513, + layout_for_ptr: #69835, + }, + Stable_1_82(82) => { + unsafe_extern_blocks: #127921, + }, + Stable_1_77(77) => { + offset_of: #106655, + literal_cstr(2021)|(2024): #117472, }, Stable_1_73(73) => { thiscall_abi: #42202 }, Stable_1_71(71) => { c_unwind_abi: #106075 }, Stable_1_68(68) => { abi_efiapi: #105795 }, Stable_1_64(64) => { core_ffi_c: #94503 }, + Stable_1_51(51) => { + raw_ref_macros: #80886, + min_const_generics: #74878, + }, Stable_1_59(59) => { const_cstr: #54745 }, Stable_1_47(47) => { larger_arrays: #74060 }, + Stable_1_43(43) => { associated_constants: #68952 }, Stable_1_40(40) => { non_exhaustive: #44109 }, Stable_1_36(36) => { maybe_uninit: #60445 }, Stable_1_33(33) => { repr_packed_n: #57049 }, - #[deprecated] - Stable_1_30(30) => { - core_ffi_c_void: #53910, - min_const_fn: #54835, - }, - #[deprecated] - Stable_1_28(28) => { repr_transparent: #51562 }, - #[deprecated] - Stable_1_27(27) => { must_use_function: #48925 }, - #[deprecated] - Stable_1_26(26) => { i128_and_u128: #49101 }, - #[deprecated] - Stable_1_25(25) => { repr_align: #47006 }, - #[deprecated] - Stable_1_21(21) => { builtin_clone_impls: #43690 }, - #[deprecated] - Stable_1_20(20) => { associated_const: #42809 }, - #[deprecated] - Stable_1_19(19) => { untagged_union: #42068 }, - #[deprecated] - Stable_1_17(17) => { static_lifetime_elision: #39265 }, - #[deprecated] - Stable_1_0(0) => {}, } -/// Latest stable release of Rust +/// Latest stable release of Rust that is supported by bindgen pub const LATEST_STABLE_RUST: RustTarget = { // FIXME: replace all this code by // ``` @@ -139,7 +287,7 @@ pub const LATEST_STABLE_RUST: RustTarget = { // .into_iter() // .max_by_key(|(_, m)| m) // .map(|(t, _)| t) - // .unwrap_or(RustTarget::Nightly) + // .unwrap() // ``` // once those operations can be used in constants. let targets = RustTarget::stable_releases(); @@ -165,132 +313,198 @@ pub const LATEST_STABLE_RUST: RustTarget = { } }; -impl Default for RustTarget { - fn default() -> Self { - LATEST_STABLE_RUST - } -} +/// Earliest stable release of Rust that is supported by bindgen +pub const EARLIEST_STABLE_RUST: RustTarget = { + // FIXME: replace all this code by + // ``` + // RustTarget::stable_releases() + // .into_iter() + // .min_by_key(|(_, m)| m) + // .map(|(t, _)| t) + // .unwrap_or(LATEST_STABLE_RUST) + // ``` + // once those operations can be used in constants. + let targets = RustTarget::stable_releases(); -impl PartialOrd for RustTarget { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} + let mut i = 0; + let mut earliest_target = None; + let Some(mut earliest_minor) = LATEST_STABLE_RUST.minor() else { + unreachable!() + }; -impl Ord for RustTarget { - fn cmp(&self, other: &Self) -> Ordering { - match (self.minor(), other.minor()) { - (Some(a), Some(b)) => a.cmp(&b), - (Some(_), None) => Ordering::Less, - (None, Some(_)) => Ordering::Greater, - (None, None) => Ordering::Equal, + while i < targets.len() { + let (target, minor) = targets[i]; + + if earliest_minor > minor { + earliest_minor = minor; + earliest_target = Some(target); } + + i += 1; + } + + match earliest_target { + Some(target) => target, + None => unreachable!(), } +}; + +fn invalid_input(input: &str, msg: impl fmt::Display) -> io::Error { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("\"{input}\" is not a valid Rust target, {msg}"), + ) } impl FromStr for RustTarget { type Err = io::Error; - fn from_str(s: &str) -> Result { - if s == "nightly" { + fn from_str(input: &str) -> Result { + if input == "nightly" { return Ok(Self::Nightly); } - if let Some(("1", str_minor)) = s.split_once('.') { - if let Ok(minor) = str_minor.parse::() { - for (target, target_minor) in Self::stable_releases() { - if minor == target_minor { - return Ok(target); - } - } - } + let Some((major_str, tail)) = input.split_once('.') else { + return Err(invalid_input(input, "accepted values are of the form \"1.71\", \"1.71.1\" or \"nightly\"." ) ); + }; + + if major_str != "1" { + return Err(invalid_input( + input, + "The largest major version of Rust released is \"1\"", + )); } - Err(io::Error::new( - io::ErrorKind::InvalidInput, - "Got an invalid Rust target. Accepted values are of the form \"1.71\" or \"nightly\"." - )) + let (minor, patch) = if let Some((minor_str, patch_str)) = + tail.split_once('.') + { + let Ok(minor) = minor_str.parse::() else { + return Err(invalid_input(input, "the minor version number must be an unsigned 64-bit integer")); + }; + let Ok(patch) = patch_str.parse::() else { + return Err(invalid_input(input, "the patch version number must be an unsigned 64-bit integer")); + }; + (minor, patch) + } else { + let Ok(minor) = tail.parse::() else { + return Err(invalid_input(input, "the minor version number must be an unsigned 64-bit integer")); + }; + (minor, 0) + }; + + Self::stable(minor, patch).map_err(|err| invalid_input(input, err)) } } -impl std::fmt::Display for RustTarget { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.minor() { - Some(minor) => write!(f, "1.{}", minor), - None => "nightly".fmt(f), - } +impl RustFeatures { + /// Compute the features that must be enabled in a specific Rust target with the latest edition + /// available in that target. + pub(crate) fn new_with_latest_edition(target: RustTarget) -> Self { + Self::new(target, target.latest_edition()) } } impl Default for RustFeatures { fn default() -> Self { - RustTarget::default().into() + Self::new_with_latest_edition(RustTarget::default()) } } #[cfg(test)] mod test { - #![allow(unused_imports)] use super::*; #[test] - fn target_features() { - let f_1_0 = RustFeatures::from(RustTarget::Stable_1_0); - assert!( - !f_1_0.static_lifetime_elision && - !f_1_0.core_ffi_c_void && - !f_1_0.untagged_union && - !f_1_0.associated_const && - !f_1_0.builtin_clone_impls && - !f_1_0.repr_align && - !f_1_0.thiscall_abi && - !f_1_0.vectorcall_abi + fn release_versions_for_editions() { + assert_eq!( + "1.33".parse::().unwrap().latest_edition(), + RustEdition::Edition2018 ); - let f_1_21 = RustFeatures::from(RustTarget::Stable_1_21); - assert!( - f_1_21.static_lifetime_elision && - !f_1_21.core_ffi_c_void && - f_1_21.untagged_union && - f_1_21.associated_const && - f_1_21.builtin_clone_impls && - !f_1_21.repr_align && - !f_1_21.thiscall_abi && - !f_1_21.vectorcall_abi + assert_eq!( + "1.56".parse::().unwrap().latest_edition(), + RustEdition::Edition2021 ); - let features = RustFeatures::from(RustTarget::Stable_1_71); + assert_eq!( + "1.85".parse::().unwrap().latest_edition(), + RustEdition::Edition2024 + ); + assert_eq!( + "nightly".parse::().unwrap().latest_edition(), + RustEdition::Edition2024 + ); + } + + #[test] + fn target_features() { + let features = + RustFeatures::new_with_latest_edition(RustTarget::Stable_1_71); assert!( features.c_unwind_abi && features.abi_efiapi && !features.thiscall_abi ); - let f_nightly = RustFeatures::from(RustTarget::Nightly); + + let features = RustFeatures::new( + RustTarget::Stable_1_77, + RustEdition::Edition2018, + ); + assert!(!features.literal_cstr); + + let features = + RustFeatures::new_with_latest_edition(RustTarget::Stable_1_77); + assert!(features.literal_cstr); + + let f_nightly = + RustFeatures::new_with_latest_edition(RustTarget::Nightly); assert!( - f_nightly.static_lifetime_elision && - f_nightly.core_ffi_c_void && - f_nightly.untagged_union && - f_nightly.associated_const && - f_nightly.builtin_clone_impls && - f_nightly.maybe_uninit && - f_nightly.repr_align && - f_nightly.thiscall_abi && - f_nightly.vectorcall_abi + f_nightly.vectorcall_abi && + f_nightly.ptr_metadata && + f_nightly.layout_for_ptr ); } - fn test_target(target_str: &str, target: RustTarget) { - let target_string = target.to_string(); - assert_eq!(target_str, target_string); - assert_eq!(target, RustTarget::from_str(target_str).unwrap()); + fn test_target(input: &str, expected: RustTarget) { + // Two targets are equivalent if they enable the same set of features + let expected = RustFeatures::new_with_latest_edition(expected); + let found = RustFeatures::new_with_latest_edition( + input.parse::().unwrap(), + ); + assert_eq!( + expected, + found, + "target {input} enables features:\n{found:#?}\nand should enable features:\n{expected:#?}" + ); + } + + fn test_invalid_target(input: &str) { + assert!( + input.parse::().is_err(), + "{input} should be an invalid target" + ); } #[test] - fn str_to_target() { - test_target("1.0", RustTarget::Stable_1_0); - test_target("1.17", RustTarget::Stable_1_17); - test_target("1.19", RustTarget::Stable_1_19); - test_target("1.21", RustTarget::Stable_1_21); - test_target("1.25", RustTarget::Stable_1_25); + fn valid_targets() { test_target("1.71", RustTarget::Stable_1_71); + test_target("1.71.0", RustTarget::Stable_1_71); + test_target("1.71.1", RustTarget::Stable_1_71); + test_target("1.72", RustTarget::Stable_1_71); + test_target("1.73", RustTarget::Stable_1_73); + test_target("1.18446744073709551615", LATEST_STABLE_RUST); test_target("nightly", RustTarget::Nightly); } + + #[test] + fn invalid_targets() { + test_invalid_target("2.0"); + test_invalid_target("1.cat"); + test_invalid_target("1.0.cat"); + test_invalid_target("1.18446744073709551616"); + test_invalid_target("1.0.18446744073709551616"); + test_invalid_target("1.-1.0"); + test_invalid_target("1.0.-1"); + test_invalid_target("beta"); + test_invalid_target("1.0.0"); + test_invalid_target("1.32.0"); + } } diff --git a/bindgen/ir/analysis/derive.rs b/bindgen/ir/analysis/derive.rs index d8d29ed9a8..eaa20fff46 100644 --- a/bindgen/ir/analysis/derive.rs +++ b/bindgen/ir/analysis/derive.rs @@ -104,7 +104,7 @@ fn consider_edge_default(kind: EdgeKind) -> bool { } } -impl<'ctx> CannotDerive<'ctx> { +impl CannotDerive<'_> { fn insert>( &mut self, id: Id, @@ -112,10 +112,8 @@ impl<'ctx> CannotDerive<'ctx> { ) -> ConstrainResult { let id = id.into(); trace!( - "inserting {:?} can_derive<{}>={:?}", - id, + "inserting {id:?} can_derive<{}>={can_derive:?}", self.derive_trait, - can_derive ); if let CanDerive::Yes = can_derive { @@ -168,7 +166,7 @@ impl<'ctx> CannotDerive<'ctx> { return CanDerive::No; } - trace!("ty: {:?}", ty); + trace!("ty: {ty:?}"); if item.is_opaque(self.ctx, &()) { if !self.derive_trait.can_derive_union() && ty.is_union() && @@ -183,7 +181,7 @@ impl<'ctx> CannotDerive<'ctx> { let layout_can_derive = ty.layout(self.ctx).map_or(CanDerive::Yes, |l| { - l.opaque().array_size_within_derive_limit(self.ctx) + l.opaque().array_size_within_derive_limit() }); match layout_can_derive { @@ -199,7 +197,7 @@ impl<'ctx> CannotDerive<'ctx> { self.derive_trait ); } - }; + } return layout_can_derive; } @@ -217,9 +215,7 @@ impl<'ctx> CannotDerive<'ctx> { TypeKind::Reference(..) | TypeKind::ObjCInterface(..) | TypeKind::ObjCId | - TypeKind::ObjCSel => { - return self.derive_trait.can_derive_simple(ty.kind()); - } + TypeKind::ObjCSel => self.derive_trait.can_derive_simple(ty.kind()), TypeKind::Pointer(inner) => { let inner_type = self.ctx.resolve_type(inner).canonical_type(self.ctx); @@ -236,7 +232,7 @@ impl<'ctx> CannotDerive<'ctx> { // Complex cases need more information TypeKind::Array(t, len) => { let inner_type = - self.can_derive.get(&t.into()).cloned().unwrap_or_default(); + self.can_derive.get(&t.into()).copied().unwrap_or_default(); if inner_type != CanDerive::Yes { trace!( " arrays of T for which we cannot derive {} \ @@ -275,7 +271,7 @@ impl<'ctx> CannotDerive<'ctx> { } TypeKind::Vector(t, len) => { let inner_type = - self.can_derive.get(&t.into()).cloned().unwrap_or_default(); + self.can_derive.get(&t.into()).copied().unwrap_or_default(); if inner_type != CanDerive::Yes { trace!( " vectors of T for which we cannot derive {} \ @@ -344,8 +340,7 @@ impl<'ctx> CannotDerive<'ctx> { let layout_can_derive = ty.layout(self.ctx).map_or(CanDerive::Yes, |l| { - l.opaque() - .array_size_within_derive_limit(self.ctx) + l.opaque().array_size_within_derive_limit() }); match layout_can_derive { CanDerive::Yes => { @@ -360,7 +355,7 @@ impl<'ctx> CannotDerive<'ctx> { self.derive_trait ); } - }; + } return layout_can_derive; } } @@ -431,13 +426,13 @@ impl<'ctx> CannotDerive<'ctx> { let can_derive = self.can_derive .get(&sub_id) - .cloned() + .copied() .unwrap_or_default(); match can_derive { - CanDerive::Yes => trace!(" member {:?} can derive {}", sub_id, self.derive_trait), - CanDerive::Manually => trace!(" member {:?} cannot derive {}, but it may be implemented", sub_id, self.derive_trait), - CanDerive::No => trace!(" member {:?} cannot derive {}", sub_id, self.derive_trait), + CanDerive::Yes => trace!(" member {sub_id:?} can derive {}", self.derive_trait), + CanDerive::Manually => trace!(" member {sub_id:?} cannot derive {}, but it may be implemented", self.derive_trait), + CanDerive::No => trace!(" member {sub_id:?} cannot derive {}", self.derive_trait), } *candidate.get_or_insert(CanDerive::Yes) |= can_derive; @@ -456,7 +451,7 @@ impl<'ctx> CannotDerive<'ctx> { } impl DeriveTrait { - fn not_by_name(&self, ctx: &BindgenContext, item: &Item) -> bool { + fn not_by_name(self, ctx: &BindgenContext, item: &Item) -> bool { match self { DeriveTrait::Copy => ctx.no_copy_by_name(item), DeriveTrait::Debug => ctx.no_debug_by_name(item), @@ -468,21 +463,21 @@ impl DeriveTrait { } } - fn consider_edge_comp(&self) -> EdgePredicate { + fn consider_edge_comp(self) -> EdgePredicate { match self { DeriveTrait::PartialEqOrPartialOrd => consider_edge_default, _ => |kind| matches!(kind, EdgeKind::BaseMember | EdgeKind::Field), } } - fn consider_edge_typeref(&self) -> EdgePredicate { + fn consider_edge_typeref(self) -> EdgePredicate { match self { DeriveTrait::PartialEqOrPartialOrd => consider_edge_default, _ => |kind| kind == EdgeKind::TypeReference, } } - fn consider_edge_tmpl_inst(&self) -> EdgePredicate { + fn consider_edge_tmpl_inst(self) -> EdgePredicate { match self { DeriveTrait::PartialEqOrPartialOrd => consider_edge_default, _ => |kind| { @@ -494,7 +489,7 @@ impl DeriveTrait { } } - fn can_derive_large_array(&self, ctx: &BindgenContext) -> bool { + fn can_derive_large_array(self, ctx: &BindgenContext) -> bool { if ctx.options().rust_features().larger_arrays { !matches!(self, DeriveTrait::Default) } else { @@ -502,23 +497,23 @@ impl DeriveTrait { } } - fn can_derive_union(&self) -> bool { + fn can_derive_union(self) -> bool { matches!(self, DeriveTrait::Copy) } - fn can_derive_compound_with_destructor(&self) -> bool { + fn can_derive_compound_with_destructor(self) -> bool { !matches!(self, DeriveTrait::Copy) } - fn can_derive_compound_with_vtable(&self) -> bool { + fn can_derive_compound_with_vtable(self) -> bool { !matches!(self, DeriveTrait::Default) } - fn can_derive_compound_forward_decl(&self) -> bool { + fn can_derive_compound_forward_decl(self) -> bool { matches!(self, DeriveTrait::Copy | DeriveTrait::Debug) } - fn can_derive_incomplete_array(&self) -> bool { + fn can_derive_incomplete_array(self) -> bool { !matches!( self, DeriveTrait::Copy | @@ -527,63 +522,60 @@ impl DeriveTrait { ) } - fn can_derive_fnptr(&self, f: &FunctionSig) -> CanDerive { + fn can_derive_fnptr(self, f: &FunctionSig) -> CanDerive { match (self, f.function_pointers_can_derive()) { - (DeriveTrait::Copy, _) | (DeriveTrait::Default, _) | (_, true) => { - trace!(" function pointer can derive {}", self); + (DeriveTrait::Copy | DeriveTrait::Default, _) | (_, true) => { + trace!(" function pointer can derive {self}"); CanDerive::Yes } (DeriveTrait::Debug, false) => { - trace!(" function pointer cannot derive {}, but it may be implemented", self); + trace!(" function pointer cannot derive {self}, but it may be implemented"); CanDerive::Manually } (_, false) => { - trace!(" function pointer cannot derive {}", self); + trace!(" function pointer cannot derive {self}"); CanDerive::No } } } - fn can_derive_vector(&self) -> CanDerive { - match self { - DeriveTrait::PartialEqOrPartialOrd => { - // FIXME: vectors always can derive PartialEq, but they should - // not derive PartialOrd: - // https://github.com/rust-lang-nursery/packed_simd/issues/48 - trace!(" vectors cannot derive PartialOrd"); - CanDerive::No - } - _ => { - trace!(" vector can derive {}", self); - CanDerive::Yes - } + fn can_derive_vector(self) -> CanDerive { + if self == DeriveTrait::PartialEqOrPartialOrd { + // FIXME: vectors always can derive PartialEq, but they should + // not derive PartialOrd: + // https://github.com/rust-lang-nursery/packed_simd/issues/48 + trace!(" vectors cannot derive PartialOrd"); + CanDerive::No + } else { + trace!(" vector can derive {self}"); + CanDerive::Yes } } - fn can_derive_pointer(&self) -> CanDerive { - match self { - DeriveTrait::Default => { - trace!(" pointer cannot derive Default"); - CanDerive::No - } - _ => { - trace!(" pointer can derive {}", self); - CanDerive::Yes - } + fn can_derive_pointer(self) -> CanDerive { + if self == DeriveTrait::Default { + trace!(" pointer cannot derive Default"); + CanDerive::No + } else { + trace!(" pointer can derive {self}"); + CanDerive::Yes } } - fn can_derive_simple(&self, kind: &TypeKind) -> CanDerive { + fn can_derive_simple(self, kind: &TypeKind) -> CanDerive { match (self, kind) { // === Default === - (DeriveTrait::Default, TypeKind::Void) | - (DeriveTrait::Default, TypeKind::NullPtr) | - (DeriveTrait::Default, TypeKind::Enum(..)) | - (DeriveTrait::Default, TypeKind::Reference(..)) | - (DeriveTrait::Default, TypeKind::TypeParam) | - (DeriveTrait::Default, TypeKind::ObjCInterface(..)) | - (DeriveTrait::Default, TypeKind::ObjCId) | - (DeriveTrait::Default, TypeKind::ObjCSel) => { + ( + DeriveTrait::Default, + TypeKind::Void | + TypeKind::NullPtr | + TypeKind::Enum(..) | + TypeKind::Reference(..) | + TypeKind::TypeParam | + TypeKind::ObjCInterface(..) | + TypeKind::ObjCId | + TypeKind::ObjCSel, + ) => { trace!(" types that always cannot derive Default"); CanDerive::No } @@ -593,14 +585,16 @@ impl DeriveTrait { ) } // === Hash === - (DeriveTrait::Hash, TypeKind::Float(..)) | - (DeriveTrait::Hash, TypeKind::Complex(..)) => { + ( + DeriveTrait::Hash, + TypeKind::Float(..) | TypeKind::Complex(..), + ) => { trace!(" float cannot derive Hash"); CanDerive::No } // === others === _ => { - trace!(" simple type that can always derive {}", self); + trace!(" simple type that can always derive {self}"); CanDerive::Yes } } @@ -645,7 +639,7 @@ impl<'ctx> MonotoneFramework for CannotDerive<'ctx> { self.ctx .allowlisted_items() .iter() - .cloned() + .copied() .flat_map(|i| { let mut reachable = vec![i]; i.trace( @@ -661,9 +655,9 @@ impl<'ctx> MonotoneFramework for CannotDerive<'ctx> { } fn constrain(&mut self, id: ItemId) -> ConstrainResult { - trace!("constrain: {:?}", id); + trace!("constrain: {id:?}"); - if let Some(CanDerive::No) = self.can_derive.get(&id).cloned() { + if let Some(CanDerive::No) = self.can_derive.get(&id) { trace!(" already know it cannot derive {}", self.derive_trait); return ConstrainResult::Same; } @@ -676,7 +670,7 @@ impl<'ctx> MonotoneFramework for CannotDerive<'ctx> { let is_reached_limit = |l: Layout| l.align > RUST_DERIVE_IN_ARRAY_LIMIT; if !self.derive_trait.can_derive_large_array(self.ctx) && - ty.layout(self.ctx).map_or(false, is_reached_limit) + ty.layout(self.ctx).is_some_and(is_reached_limit) { // We have to be conservative: the struct *could* have enough // padding that we emit an array that is longer than @@ -700,7 +694,7 @@ impl<'ctx> MonotoneFramework for CannotDerive<'ctx> { { if let Some(edges) = self.dependencies.get(&id) { for item in edges { - trace!("enqueue {:?} into worklist", item); + trace!("enqueue {item:?} into worklist"); f(*item); } } @@ -727,6 +721,6 @@ pub(crate) fn as_cannot_derive_set( ) -> HashSet { can_derive .into_iter() - .filter_map(|(k, v)| if v != CanDerive::Yes { Some(k) } else { None }) + .filter_map(|(k, v)| if v == CanDerive::Yes { None } else { Some(k) }) .collect() } diff --git a/bindgen/ir/analysis/has_destructor.rs b/bindgen/ir/analysis/has_destructor.rs index cbcbe55af2..4893f8f807 100644 --- a/bindgen/ir/analysis/has_destructor.rs +++ b/bindgen/ir/analysis/has_destructor.rs @@ -39,7 +39,7 @@ pub(crate) struct HasDestructorAnalysis<'ctx> { dependencies: HashMap>, } -impl<'ctx> HasDestructorAnalysis<'ctx> { +impl HasDestructorAnalysis<'_> { fn consider_edge(kind: EdgeKind) -> bool { // These are the only edges that can affect whether a type has a // destructor or not. @@ -58,9 +58,8 @@ impl<'ctx> HasDestructorAnalysis<'ctx> { let was_not_already_in_set = self.have_destructor.insert(id); assert!( was_not_already_in_set, - "We shouldn't try and insert {:?} twice because if it was \ - already in the set, `constrain` should have exited early.", - id + "We shouldn't try and insert {id:?} twice because if it was \ + already in the set, `constrain` should have exited early." ); ConstrainResult::Changed } @@ -83,7 +82,7 @@ impl<'ctx> MonotoneFramework for HasDestructorAnalysis<'ctx> { } fn initial_worklist(&self) -> Vec { - self.ctx.allowlisted_items().iter().cloned().collect() + self.ctx.allowlisted_items().iter().copied().collect() } fn constrain(&mut self, id: ItemId) -> ConstrainResult { @@ -162,7 +161,7 @@ impl<'ctx> MonotoneFramework for HasDestructorAnalysis<'ctx> { { if let Some(edges) = self.dependencies.get(&id) { for item in edges { - trace!("enqueue {:?} into worklist", item); + trace!("enqueue {item:?} into worklist"); f(*item); } } diff --git a/bindgen/ir/analysis/has_float.rs b/bindgen/ir/analysis/has_float.rs index 219c5a5a8d..e2463ccb96 100644 --- a/bindgen/ir/analysis/has_float.rs +++ b/bindgen/ir/analysis/has_float.rs @@ -39,7 +39,7 @@ pub(crate) struct HasFloat<'ctx> { dependencies: HashMap>, } -impl<'ctx> HasFloat<'ctx> { +impl HasFloat<'_> { fn consider_edge(kind: EdgeKind) -> bool { match kind { EdgeKind::BaseMember | @@ -56,21 +56,20 @@ impl<'ctx> HasFloat<'ctx> { EdgeKind::FunctionParameter | EdgeKind::InnerType | EdgeKind::InnerVar | - EdgeKind::Method => false, + EdgeKind::Method | EdgeKind::Generic => false, } } fn insert>(&mut self, id: Id) -> ConstrainResult { let id = id.into(); - trace!("inserting {:?} into the has_float set", id); + trace!("inserting {id:?} into the has_float set"); let was_not_already_in_set = self.has_float.insert(id); assert!( was_not_already_in_set, - "We shouldn't try and insert {:?} twice because if it was \ - already in the set, `constrain` should have exited early.", - id + "We shouldn't try and insert {id:?} twice because if it was \ + already in the set, `constrain` should have exited early." ); ConstrainResult::Changed @@ -94,11 +93,11 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { } fn initial_worklist(&self) -> Vec { - self.ctx.allowlisted_items().iter().cloned().collect() + self.ctx.allowlisted_items().iter().copied().collect() } fn constrain(&mut self, id: ItemId) -> ConstrainResult { - trace!("constrain: {:?}", id); + trace!("constrain: {id:?}"); if self.has_float.contains(&id) { trace!(" already know it do not have float"); @@ -106,12 +105,9 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { } let item = self.ctx.resolve_item(id); - let ty = match item.as_type() { - Some(ty) => ty, - None => { - trace!(" not a type; ignoring"); - return ConstrainResult::Same; - } + let Some(ty) = item.as_type() else { + trace!(" not a type; ignoring"); + return ConstrainResult::Same; }; match *ty.kind() { @@ -210,7 +206,7 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { if args_have { trace!( " template args have float, so \ - insantiation also has float" + instantiation also has float" ); return self.insert(id); } @@ -221,7 +217,7 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { if def_has { trace!( " template definition has float, so \ - insantiation also has" + instantiation also has" ); return self.insert(id); } @@ -238,7 +234,7 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { { if let Some(edges) = self.dependencies.get(&id) { for item in edges { - trace!("enqueue {:?} into worklist", item); + trace!("enqueue {item:?} into worklist"); f(*item); } } diff --git a/bindgen/ir/analysis/has_type_param_in_array.rs b/bindgen/ir/analysis/has_type_param_in_array.rs index 088c08f542..687f81560c 100644 --- a/bindgen/ir/analysis/has_type_param_in_array.rs +++ b/bindgen/ir/analysis/has_type_param_in_array.rs @@ -17,7 +17,7 @@ use crate::{HashMap, HashSet}; /// * If T is a type alias, a templated alias or an indirection to another type, /// it has type parameter in array if the type T refers to has. /// * If T is a compound type, it has array if any of base memter or field -/// has type paramter in array. +/// has type parameter in array. /// * If T is an instantiation of an abstract template definition, T has /// type parameter in array if any of the template arguments or template definition /// has. @@ -39,7 +39,7 @@ pub(crate) struct HasTypeParameterInArray<'ctx> { dependencies: HashMap>, } -impl<'ctx> HasTypeParameterInArray<'ctx> { +impl HasTypeParameterInArray<'_> { fn consider_edge(kind: EdgeKind) -> bool { match kind { // These are the only edges that can affect whether a type has type parameter @@ -58,25 +58,21 @@ impl<'ctx> HasTypeParameterInArray<'ctx> { EdgeKind::FunctionParameter | EdgeKind::InnerType | EdgeKind::InnerVar | - EdgeKind::Method => false, + EdgeKind::Method | EdgeKind::Generic => false, } } fn insert>(&mut self, id: Id) -> ConstrainResult { let id = id.into(); - trace!( - "inserting {:?} into the has_type_parameter_in_array set", - id - ); + trace!("inserting {id:?} into the has_type_parameter_in_array set"); let was_not_already_in_set = self.has_type_parameter_in_array.insert(id); assert!( was_not_already_in_set, - "We shouldn't try and insert {:?} twice because if it was \ - already in the set, `constrain` should have exited early.", - id + "We shouldn't try and insert {id:?} twice because if it was \ + already in the set, `constrain` should have exited early." ); ConstrainResult::Changed @@ -100,11 +96,11 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { } fn initial_worklist(&self) -> Vec { - self.ctx.allowlisted_items().iter().cloned().collect() + self.ctx.allowlisted_items().iter().copied().collect() } fn constrain(&mut self, id: ItemId) -> ConstrainResult { - trace!("constrain: {:?}", id); + trace!("constrain: {id:?}"); if self.has_type_parameter_in_array.contains(&id) { trace!(" already know it do not have array"); @@ -112,12 +108,9 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { } let item = self.ctx.resolve_item(id); - let ty = match item.as_type() { - Some(ty) => ty, - None => { - trace!(" not a type; ignoring"); - return ConstrainResult::Same; - } + let Some(ty) = item.as_type() else { + trace!(" not a type; ignoring"); + return ConstrainResult::Same; }; match *ty.kind() { @@ -146,17 +139,14 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { TypeKind::Array(t, _) => { let inner_ty = self.ctx.resolve_type(t).canonical_type(self.ctx); - match *inner_ty.kind() { - TypeKind::TypeParam => { - trace!(" Array with Named type has type parameter"); - self.insert(id) - } - _ => { - trace!( - " Array without Named type does have type parameter" - ); - ConstrainResult::Same - } + if let TypeKind::TypeParam = *inner_ty.kind() { + trace!(" Array with Named type has type parameter"); + self.insert(id) + } else { + trace!( + " Array without Named type does have type parameter" + ); + ConstrainResult::Same } } @@ -210,7 +200,7 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { if args_have { trace!( " template args have array, so \ - insantiation also has array" + instantiation also has array" ); return self.insert(id); } @@ -221,7 +211,7 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { if def_has { trace!( " template definition has array, so \ - insantiation also has" + instantiation also has" ); return self.insert(id); } @@ -238,7 +228,7 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { { if let Some(edges) = self.dependencies.get(&id) { for item in edges { - trace!("enqueue {:?} into worklist", item); + trace!("enqueue {item:?} into worklist"); f(*item); } } diff --git a/bindgen/ir/analysis/has_vtable.rs b/bindgen/ir/analysis/has_vtable.rs index 980a551b88..3ff64a6d2b 100644 --- a/bindgen/ir/analysis/has_vtable.rs +++ b/bindgen/ir/analysis/has_vtable.rs @@ -9,9 +9,10 @@ use std::cmp; use std::ops; /// The result of the `HasVtableAnalysis` for an individual item. -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Default)] pub(crate) enum HasVtableResult { /// The item does not have a vtable pointer. + #[default] No, /// The item has a vtable and the actual vtable pointer is within this item. @@ -22,12 +23,6 @@ pub(crate) enum HasVtableResult { BaseHasVtable, } -impl Default for HasVtableResult { - fn default() -> Self { - HasVtableResult::No - } -} - impl HasVtableResult { /// Take the least upper bound of `self` and `rhs`. pub(crate) fn join(self, rhs: Self) -> Self { @@ -45,7 +40,7 @@ impl ops::BitOr for HasVtableResult { impl ops::BitOrAssign for HasVtableResult { fn bitor_assign(&mut self, rhs: HasVtableResult) { - *self = self.join(rhs) + *self = self.join(rhs); } } @@ -77,7 +72,7 @@ pub(crate) struct HasVtableAnalysis<'ctx> { dependencies: HashMap>, } -impl<'ctx> HasVtableAnalysis<'ctx> { +impl HasVtableAnalysis<'_> { fn consider_edge(kind: EdgeKind) -> bool { // These are the only edges that can affect whether a type has a // vtable or not. @@ -123,9 +118,9 @@ impl<'ctx> HasVtableAnalysis<'ctx> { let from = from.into(); let to = to.into(); - match self.have_vtable.get(&from).cloned() { + match self.have_vtable.get(&from) { None => ConstrainResult::Same, - Some(r) => self.insert(to, r), + Some(r) => self.insert(to, *r), } } } @@ -147,11 +142,11 @@ impl<'ctx> MonotoneFramework for HasVtableAnalysis<'ctx> { } fn initial_worklist(&self) -> Vec { - self.ctx.allowlisted_items().iter().cloned().collect() + self.ctx.allowlisted_items().iter().copied().collect() } fn constrain(&mut self, id: ItemId) -> ConstrainResult { - trace!("constrain {:?}", id); + trace!("constrain {id:?}"); let item = self.ctx.resolve_item(id); let ty = match item.as_type() { @@ -181,7 +176,7 @@ impl<'ctx> MonotoneFramework for HasVtableAnalysis<'ctx> { } let bases_has_vtable = info.base_members().iter().any(|base| { - trace!(" comp has a base with a vtable: {:?}", base); + trace!(" comp has a base with a vtable: {base:?}"); self.have_vtable.contains_key(&base.ty.into()) }); if bases_has_vtable { @@ -205,7 +200,7 @@ impl<'ctx> MonotoneFramework for HasVtableAnalysis<'ctx> { { if let Some(edges) = self.dependencies.get(&id) { for item in edges { - trace!("enqueue {:?} into worklist", item); + trace!("enqueue {item:?} into worklist"); f(*item); } } @@ -228,7 +223,7 @@ impl<'ctx> From> for HashMap { /// vtable during codegen. /// /// This is not for _computing_ whether the thing has a vtable, it is for -/// looking up the results of the HasVtableAnalysis's computations for a +/// looking up the results of the `HasVtableAnalysis`'s computations for a /// specific thing. pub(crate) trait HasVtable { /// Return `true` if this thing has vtable, `false` otherwise. diff --git a/bindgen/ir/analysis/mod.rs b/bindgen/ir/analysis/mod.rs index 443384a487..74a305edfb 100644 --- a/bindgen/ir/analysis/mod.rs +++ b/bindgen/ir/analysis/mod.rs @@ -125,22 +125,17 @@ pub(crate) trait MonotoneFramework: Sized + fmt::Debug { /// Whether an analysis's `constrain` function modified the incremental results /// or not. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] pub(crate) enum ConstrainResult { /// The incremental results were updated, and the fix-point computation /// should continue. Changed, /// The incremental results were not updated. + #[default] Same, } -impl Default for ConstrainResult { - fn default() -> Self { - ConstrainResult::Same - } -} - impl ops::BitOr for ConstrainResult { type Output = Self; @@ -216,7 +211,7 @@ where #[cfg(test)] mod tests { use super::*; - use crate::{HashMap, HashSet}; + use crate::HashSet; // Here we find the set of nodes that are reachable from any given // node. This is a lattice mapping nodes to subsets of all nodes. Our join @@ -285,9 +280,9 @@ mod tests { fn reverse(&self) -> Graph { let mut reversed = Graph::default(); - for (node, edges) in self.0.iter() { + for (node, edges) in &self.0 { reversed.0.entry(*node).or_insert_with(Vec::new); - for referent in edges.iter() { + for referent in edges { reversed .0 .entry(*referent) @@ -311,7 +306,7 @@ mod tests { type Extra = &'a Graph; type Output = HashMap>; - fn new(graph: &'a Graph) -> ReachableFrom { + fn new(graph: &'a Graph) -> Self { let reversed = graph.reverse(); ReachableFrom { reachable: Default::default(), @@ -321,7 +316,7 @@ mod tests { } fn initial_worklist(&self) -> Vec { - self.graph.0.keys().cloned().collect() + self.graph.0.keys().copied().collect() } fn constrain(&mut self, node: Node) -> ConstrainResult { @@ -336,7 +331,7 @@ mod tests { let original_size = self.reachable.entry(node).or_default().len(); - for sub_node in self.graph.0[&node].iter() { + for sub_node in &self.graph.0[&node] { self.reachable.get_mut(&node).unwrap().insert(*sub_node); let sub_reachable = @@ -348,10 +343,10 @@ mod tests { } let new_size = self.reachable[&node].len(); - if original_size != new_size { - ConstrainResult::Changed - } else { + if original_size == new_size { ConstrainResult::Same + } else { + ConstrainResult::Changed } } @@ -359,7 +354,7 @@ mod tests { where F: FnMut(Node), { - for dep in self.reversed.0[&node].iter() { + for dep in &self.reversed.0[&node] { f(*dep); } } @@ -375,13 +370,13 @@ mod tests { fn monotone() { let g = Graph::make_test_graph(); let reachable = analyze::(&g); - println!("reachable = {:#?}", reachable); + println!("reachable = {reachable:#?}"); fn nodes
(nodes: A) -> HashSet where A: AsRef<[usize]>, { - nodes.as_ref().iter().cloned().map(Node).collect() + nodes.as_ref().iter().copied().map(Node).collect() } let mut expected = HashMap::default(); @@ -393,7 +388,7 @@ mod tests { expected.insert(Node(6), nodes([8])); expected.insert(Node(7), nodes([3, 4, 5, 6, 7, 8])); expected.insert(Node(8), nodes([])); - println!("expected = {:#?}", expected); + println!("expected = {expected:#?}"); assert_eq!(reachable, expected); } diff --git a/bindgen/ir/analysis/sizedness.rs b/bindgen/ir/analysis/sizedness.rs index 995d700794..ce3c2c3da1 100644 --- a/bindgen/ir/analysis/sizedness.rs +++ b/bindgen/ir/analysis/sizedness.rs @@ -24,13 +24,14 @@ use std::{cmp, ops}; /// /// We initially assume that all types are `ZeroSized` and then update our /// understanding as we learn more about each type. -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Default)] pub(crate) enum SizednessResult { /// The type is zero-sized. /// /// This means that if it is a C++ type, and is not being used as a base /// member, then we must add an `_address` byte to enforce the /// unique-address-per-distinct-object-instance rule. + #[default] ZeroSized, /// Whether this type is zero-sized or not depends on whether a type @@ -62,12 +63,6 @@ pub(crate) enum SizednessResult { NonZeroSized, } -impl Default for SizednessResult { - fn default() -> Self { - SizednessResult::ZeroSized - } -} - impl SizednessResult { /// Take the least upper bound of `self` and `rhs`. pub(crate) fn join(self, rhs: Self) -> Self { @@ -85,20 +80,20 @@ impl ops::BitOr for SizednessResult { impl ops::BitOrAssign for SizednessResult { fn bitor_assign(&mut self, rhs: SizednessResult) { - *self = self.join(rhs) + *self = self.join(rhs); } } /// An analysis that computes the sizedness of all types. /// /// * For types with known sizes -- for example pointers, scalars, etc... -- -/// they are assigned `NonZeroSized`. +/// they are assigned `NonZeroSized`. /// /// * For compound structure types with one or more fields, they are assigned -/// `NonZeroSized`. +/// `NonZeroSized`. /// /// * For compound structure types without any fields, the results of the bases -/// are `join`ed. +/// are `join`ed. /// /// * For type parameters, `DependsOnTypeParam` is assigned. #[derive(Debug)] @@ -110,7 +105,7 @@ pub(crate) struct SizednessAnalysis<'ctx> { sized: HashMap, } -impl<'ctx> SizednessAnalysis<'ctx> { +impl SizednessAnalysis<'_> { fn consider_edge(kind: EdgeKind) -> bool { // These are the only edges that can affect whether a type is // zero-sized or not. @@ -132,7 +127,7 @@ impl<'ctx> SizednessAnalysis<'ctx> { id: TypeId, result: SizednessResult, ) -> ConstrainResult { - trace!("inserting {:?} for {:?}", result, id); + trace!("inserting {result:?} for {id:?}"); if let SizednessResult::ZeroSized = result { return ConstrainResult::Same; @@ -155,9 +150,9 @@ impl<'ctx> SizednessAnalysis<'ctx> { } fn forward(&mut self, from: TypeId, to: TypeId) -> ConstrainResult { - match self.sized.get(&from).cloned() { + match self.sized.get(&from) { None => ConstrainResult::Same, - Some(r) => self.insert(to, r), + Some(r) => self.insert(to, *r), } } } @@ -196,17 +191,14 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { self.ctx .allowlisted_items() .iter() - .cloned() .filter_map(|id| id.as_type_id(self.ctx)) .collect() } fn constrain(&mut self, id: TypeId) -> ConstrainResult { - trace!("constrain {:?}", id); + trace!("constrain {id:?}"); - if let Some(SizednessResult::NonZeroSized) = - self.sized.get(&id).cloned() - { + if let Some(SizednessResult::NonZeroSized) = self.sized.get(&id) { trace!(" already know it is not zero-sized"); return ConstrainResult::Same; } @@ -327,7 +319,7 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { { if let Some(edges) = self.dependencies.get(&id) { for ty in edges { - trace!("enqueue {:?} into worklist", ty); + trace!("enqueue {ty:?} into worklist"); f(*ty); } } diff --git a/bindgen/ir/analysis/template_params.rs b/bindgen/ir/analysis/template_params.rs index e4261cf675..df8f861cfe 100644 --- a/bindgen/ir/analysis/template_params.rs +++ b/bindgen/ir/analysis/template_params.rs @@ -124,8 +124,8 @@ use crate::{HashMap, HashSet}; /// ``` /// /// * Finally, for all other IR item kinds, we use our lattice's `join` -/// operation: set union with each successor of the given item's template -/// parameter usage: +/// operation: set union with each successor of the given item's template +/// parameter usage: /// /// ```ignore /// template_param_usage(v) = @@ -161,7 +161,7 @@ pub(crate) struct UsedTemplateParameters<'ctx> { allowlisted_items: HashSet, } -impl<'ctx> UsedTemplateParameters<'ctx> { +impl UsedTemplateParameters<'_> { fn consider_edge(kind: EdgeKind) -> bool { match kind { // For each of these kinds of edges, if the referent uses a template @@ -259,7 +259,6 @@ impl<'ctx> UsedTemplateParameters<'ctx> { a's used template param set should be `Some`", ) .iter() - .cloned() }); used_by_this_id.extend(args); @@ -291,10 +290,8 @@ impl<'ctx> UsedTemplateParameters<'ctx> { for (arg, param) in args.iter().zip(params.iter()) { trace!( - " instantiation's argument {:?} is used if definition's \ - parameter {:?} is used", - arg, - param + " instantiation's argument {arg:?} is used if definition's \ + parameter {param:?} is used", ); if used_by_def.contains(¶m.into()) { @@ -322,8 +319,7 @@ impl<'ctx> UsedTemplateParameters<'ctx> { arg's used template param set should be \ `Some`", ) - .iter() - .cloned(); + .iter(); used_by_this_id.extend(used_by_arg); } } @@ -355,12 +351,10 @@ impl<'ctx> UsedTemplateParameters<'ctx> { sub_id's used template param set should be \ `Some`", ) - .iter() - .cloned(); + .iter(); trace!( - " union with {:?}'s usage: {:?}", - sub_id, + " union with {sub_id:?}'s usage: {:?}", used_by_sub_id.clone().collect::>() ); @@ -380,11 +374,11 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { let mut used = HashMap::default(); let mut dependencies = HashMap::default(); let allowlisted_items: HashSet<_> = - ctx.allowlisted_items().iter().cloned().collect(); + ctx.allowlisted_items().iter().copied().collect(); let allowlisted_and_blocklisted_items: ItemSet = allowlisted_items .iter() - .cloned() + .copied() .flat_map(|i| { let mut reachable = vec![i]; i.trace( @@ -470,7 +464,7 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { // (This is so that every item we call `constrain` on is guaranteed // to have a set of template parameters, and we can allow // blocklisted templates to use all of their parameters). - for item in allowlisted_items.iter() { + for item in &allowlisted_items { extra_assert!(used.contains_key(item)); extra_assert!(dependencies.contains_key(item)); item.trace( @@ -480,7 +474,7 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { extra_assert!(dependencies.contains_key(&sub_item)); }, &(), - ) + ); } } @@ -498,7 +492,7 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { self.ctx .allowlisted_items() .iter() - .cloned() + .copied() .flat_map(|i| { let mut reachable = vec![i]; i.trace( @@ -524,8 +518,8 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { // an analog to slice::split_at_mut. let mut used_by_this_id = self.take_this_id_usage_set(id); - trace!("constrain {:?}", id); - trace!(" initially, used set is {:?}", used_by_this_id); + trace!("constrain {id:?}"); + trace!(" initially, used set is {used_by_this_id:?}"); let original_len = used_by_this_id.len(); @@ -562,7 +556,7 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { _ => self.constrain_join(&mut used_by_this_id, item), } - trace!(" finally, used set is {:?}", used_by_this_id); + trace!(" finally, used set is {used_by_this_id:?}"); let new_len = used_by_this_id.len(); assert!( @@ -576,10 +570,10 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { self.used.insert(id, Some(used_by_this_id)); extra_assert!(self.used.values().all(|v| v.is_some())); - if new_len != original_len { - ConstrainResult::Changed - } else { + if new_len == original_len { ConstrainResult::Same + } else { + ConstrainResult::Changed } } @@ -589,7 +583,7 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { { if let Some(edges) = self.dependencies.get(&item) { for item in edges { - trace!("enqueue {:?} into worklist", item); + trace!("enqueue {item:?} into worklist"); f(*item); } } diff --git a/bindgen/ir/annotations.rs b/bindgen/ir/annotations.rs index 9165f3d39a..7f5d74b3ee 100644 --- a/bindgen/ir/annotations.rs +++ b/bindgen/ir/annotations.rs @@ -9,13 +9,14 @@ use std::str::FromStr; use crate::clang; /// What kind of visibility modifier should be used for a struct or field? -#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] +#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Default)] pub enum FieldVisibilityKind { /// Fields are marked as private, i.e., struct Foo {bar: bool} Private, /// Fields are marked as crate public, i.e., struct Foo {pub(crate) bar: bool} PublicCrate, /// Fields are marked as public, i.e., struct Foo {pub bar: bool} + #[default] Public, } @@ -27,7 +28,7 @@ impl FromStr for FieldVisibilityKind { "private" => Ok(Self::Private), "crate" => Ok(Self::PublicCrate), "public" => Ok(Self::Public), - _ => Err(format!("Invalid visibility kind: `{}`", s)), + _ => Err(format!("Invalid visibility kind: `{s}`")), } } } @@ -44,12 +45,6 @@ impl std::fmt::Display for FieldVisibilityKind { } } -impl Default for FieldVisibilityKind { - fn default() -> Self { - FieldVisibilityKind::Public - } -} - /// What kind of accessor should we provide for a field? #[derive(Copy, PartialEq, Eq, Clone, Debug)] pub(crate) enum FieldAccessorKind { @@ -107,6 +102,8 @@ pub(crate) struct Annotations { constify_enum_variant: bool, /// List of explicit derives for this type. derives: Vec, + /// List of explicit attributes for this type. + attributes: Vec, } fn parse_accessor(s: &str) -> FieldAccessorKind { @@ -174,6 +171,11 @@ impl Annotations { &self.derives } + /// The list of attributes that have been specified in this annotation. + pub(crate) fn attributes(&self) -> &[String] { + &self.attributes + } + /// Should we avoid implementing the `Copy` trait? pub(crate) fn disallow_copy(&self) -> bool { self.disallow_copy @@ -211,7 +213,7 @@ impl Annotations { comment .get_tag_attrs() .next() - .map_or(false, |attr| attr.name == "rustbindgen") + .is_some_and(|attr| attr.name == "rustbindgen") { *matched = true; for attr in comment.get_tag_attrs() { @@ -225,18 +227,19 @@ impl Annotations { "replaces" => { self.use_instead_of = Some( attr.value.split("::").map(Into::into).collect(), - ) + ); } "derive" => self.derives.push(attr.value), + "attribute" => self.attributes.push(attr.value), "private" => { - self.visibility_kind = if attr.value != "false" { - Some(FieldVisibilityKind::Private) - } else { + self.visibility_kind = if attr.value == "false" { Some(FieldVisibilityKind::Public) + } else { + Some(FieldVisibilityKind::Private) }; } "accessor" => { - self.accessor_kind = Some(parse_accessor(&attr.value)) + self.accessor_kind = Some(parse_accessor(&attr.value)); } "constant" => self.constify_enum_variant = true, _ => {} diff --git a/bindgen/ir/comment.rs b/bindgen/ir/comment.rs index 7b6f105a4d..a4ba320186 100644 --- a/bindgen/ir/comment.rs +++ b/bindgen/ir/comment.rs @@ -13,7 +13,7 @@ enum Kind { /// Preprocesses a C/C++ comment so that it is a valid Rust comment. pub(crate) fn preprocess(comment: &str) -> String { - match self::kind(comment) { + match kind(comment) { Some(Kind::SingleLines) => preprocess_single_lines(comment), Some(Kind::MultiLine) => preprocess_multi_line(comment), None => comment.to_owned(), @@ -58,7 +58,7 @@ fn preprocess_multi_line(comment: &str) -> String { .collect(); // Remove the trailing line corresponding to the `*/`. - if lines.last().map_or(false, |l| l.trim().is_empty()) { + if lines.last().is_some_and(|l| l.trim().is_empty()) { lines.pop(); } diff --git a/bindgen/ir/comp.rs b/bindgen/ir/comp.rs index bd4d016261..655e0f1fa5 100644 --- a/bindgen/ir/comp.rs +++ b/bindgen/ir/comp.rs @@ -56,16 +56,16 @@ pub(crate) enum MethodKind { impl MethodKind { /// Is this a destructor method? - pub(crate) fn is_destructor(&self) -> bool { + pub(crate) fn is_destructor(self) -> bool { matches!( - *self, + self, MethodKind::Destructor | MethodKind::VirtualDestructor { .. } ) } /// Is this a pure virtual method? - pub(crate) fn is_pure_virtual(&self) -> bool { - match *self { + pub(crate) fn is_pure_virtual(self) -> bool { + match self { MethodKind::Virtual { pure_virtual } | MethodKind::VirtualDestructor { pure_virtual } => pure_virtual, _ => false, @@ -782,7 +782,7 @@ impl CompFields { getter }; let setter = { - let setter = format!("set_{}", bitfield_name); + let setter = format!("set_{bitfield_name}"); let mut setter = ctx.rust_mangle(&setter).to_string(); if has_method(methods, ctx, &setter) { setter.push_str("_bindgen_bitfield"); @@ -803,9 +803,8 @@ impl CompFields { anon_field_counter += 1; *name = Some(format!( - "{}{}", + "{}{anon_field_counter}", ctx.options().anon_fields_prefix, - anon_field_counter )); } Field::Bitfields(ref mut bu) => { @@ -825,6 +824,23 @@ impl CompFields { } } } + + /// Return the flex array member for the struct/class, if any. + fn flex_array_member(&self, ctx: &BindgenContext) -> Option { + let fields = match self { + CompFields::Before(_) => panic!("raw fields"), + CompFields::After { fields, .. } => fields, + CompFields::Error => return None, // panic? + }; + + match fields.last()? { + Field::Bitfields(..) => None, + Field::DataMember(FieldData { ty, .. }) => ctx + .resolve_type(*ty) + .is_incomplete_array(ctx) + .map(|item| item.expect_type_id(ctx)), + } + } } impl Trace for CompFields { @@ -931,7 +947,7 @@ pub(crate) struct Base { pub(crate) kind: BaseKind, /// Name of the field in which this base should be stored. pub(crate) field_name: String, - /// Whether this base is inherited from publically. + /// Whether this base is inherited from publicly. pub(crate) is_pub: bool, } @@ -961,7 +977,7 @@ impl Base { true } - /// Whether this base is inherited from publically. + /// Whether this base is inherited from publicly. pub(crate) fn is_public(&self) -> bool { self.is_pub } @@ -1001,6 +1017,7 @@ pub(crate) struct CompInfo { /// The inner types that were declared inside this class, in something like: /// + /// ```c++ /// class Foo { /// typedef int FooTy; /// struct Bar { @@ -1009,6 +1026,7 @@ pub(crate) struct CompInfo { /// } /// /// static Foo::Bar const = {3}; + /// ``` inner_types: Vec, /// Set of static constants declared inside this class. @@ -1027,7 +1045,7 @@ pub(crate) struct CompInfo { has_nonempty_base: bool, /// If this type has a template parameter which is not a type (e.g.: a - /// size_t) + /// `size_t`) has_non_type_template_params: bool, /// Whether this type has a bit field member whose width couldn't be @@ -1040,7 +1058,7 @@ pub(crate) struct CompInfo { /// Used to know if we've found an opaque attribute that could cause us to /// generate a type with invalid layout. This is explicitly used to avoid us - /// generating bad alignments when parsing types like max_align_t. + /// generating bad alignments when parsing types like `max_align_t`. /// /// It's not clear what the behavior should be here, if generating the item /// and pray, or behave as an opaque type. @@ -1082,7 +1100,7 @@ impl CompInfo { /// /// If we're a union without known layout, we try to compute it from our /// members. This is not ideal, but clang fails to report the size for these - /// kind of unions, see test/headers/template_union.hpp + /// kind of unions, see `test/headers/template_union.hpp` pub(crate) fn layout(&self, ctx: &BindgenContext) -> Option { // We can't do better than clang here, sorry. if self.kind == CompKind::Struct { @@ -1122,6 +1140,14 @@ impl CompInfo { } } + /// Return the flex array member and its element type if any + pub(crate) fn flex_array_member( + &self, + ctx: &BindgenContext, + ) -> Option { + self.fields.flex_array_member(ctx) + } + fn has_fields(&self) -> bool { match self.fields { CompFields::Error => false, @@ -1138,14 +1164,14 @@ impl CompInfo { match self.fields { CompFields::Error => {} CompFields::After { ref fields, .. } => { - for field in fields.iter() { + for field in fields { if let Some(layout) = field.layout(ctx) { callback(layout); } } } CompFields::Before(ref raw_fields) => { - for field in raw_fields.iter() { + for field in raw_fields { let field_ty = ctx.resolve_type(field.0.ty); if let Some(layout) = field_ty.layout(ctx) { callback(layout); @@ -1189,7 +1215,7 @@ impl CompInfo { } /// Do we see a virtual function during parsing? - /// Get the has_own_virtual_method boolean. + /// Get the `has_own_virtual_method` boolean. pub(crate) fn has_own_virtual_method(&self) -> bool { self.has_own_virtual_method } @@ -1253,7 +1279,7 @@ impl CompInfo { let kind = kind?; - debug!("CompInfo::from_ty({:?}, {:?})", kind, cursor); + debug!("CompInfo::from_ty({kind:?}, {cursor:?})"); let mut ci = CompInfo::new(kind); ci.is_forward_declaration = @@ -1424,7 +1450,7 @@ impl CompInfo { } CXCursor_TemplateTypeParameter => { let param = Item::type_param(None, cur, ctx).expect( - "Item::type_param should't fail when pointing \ + "Item::type_param shouldn't fail when pointing \ at a TemplateTypeParameter", ); ci.template_params.push(param); @@ -1441,7 +1467,7 @@ impl CompInfo { let field_name = match ci.base_members.len() { 0 => "_base".into(), - n => format!("_base_{}", n), + n => format!("_base_{n}"), }; let type_id = Item::from_ty_or_ref(cur.cur_type(), cur, None, ctx); @@ -1449,8 +1475,7 @@ impl CompInfo { ty: type_id, kind, field_name, - is_pub: cur.access_specifier() == - clang_sys::CX_CXXPublic, + is_pub: cur.access_specifier() == CX_CXXPublic, }); } CXCursor_Constructor | CXCursor_Destructor | @@ -1589,7 +1614,7 @@ impl CompInfo { _ => CompKind::Struct, }, _ => { - warn!("Unknown kind for comp type: {:?}", cursor); + warn!("Unknown kind for comp type: {cursor:?}"); return Err(ParseError::Continue); } }) @@ -1649,7 +1674,7 @@ impl CompInfo { pub(crate) fn already_packed(&self, ctx: &BindgenContext) -> Option { let mut total_size: usize = 0; - for field in self.fields().iter() { + for field in self.fields() { let layout = field.layout(ctx)?; if layout.align != 0 && total_size % layout.align != 0 { @@ -1674,7 +1699,7 @@ impl CompInfo { layout: Option<&Layout>, ) { let packed = self.is_packed(ctx, layout); - self.fields.compute_bitfield_units(ctx, packed) + self.fields.compute_bitfield_units(ctx, packed); } /// Assign for each anonymous field a generated name. @@ -1685,12 +1710,12 @@ impl CompInfo { /// Returns whether the current union can be represented as a Rust `union` /// /// Requirements: - /// 1. Current RustTarget allows for `untagged_union` - /// 2. Each field can derive `Copy` or we use ManuallyDrop. + /// 1. Current `RustTarget` allows for `untagged_union` + /// 2. Each field can derive `Copy` or we use `ManuallyDrop`. /// 3. It's not zero-sized. /// /// Second boolean returns whether all fields can be copied (and thus - /// ManuallyDrop is not needed). + /// `ManuallyDrop` is not needed). pub(crate) fn is_rust_union( &self, ctx: &BindgenContext, @@ -1728,7 +1753,7 @@ impl CompInfo { return (false, false); } - if layout.map_or(false, |l| l.size == 0) { + if layout.is_some_and(|l| l.size == 0) { return (false, false); } @@ -1830,7 +1855,7 @@ impl IsOpaque for CompInfo { // See https://github.com/rust-lang/rust-bindgen/issues/537 and // https://github.com/rust-lang/rust/issues/33158 if self.is_packed(ctx, layout.as_ref()) && - layout.map_or(false, |l| l.align > 1) + layout.is_some_and(|l| l.align > 1) { warn!("Found a type that is both packed and aligned to greater than \ 1; Rust before version 1.33 doesn't have `#[repr(packed(N))]`, so we \ diff --git a/bindgen/ir/context.rs b/bindgen/ir/context.rs index f13f34abcd..3f9e16ac9b 100644 --- a/bindgen/ir/context.rs +++ b/bindgen/ir/context.rs @@ -29,8 +29,8 @@ use quote::ToTokens; use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::collections::{BTreeSet, HashMap as StdHashMap}; -use std::iter::IntoIterator; use std::mem; +use std::path::Path; /// An identifier for some kind of IR item. #[derive(Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash)] @@ -196,8 +196,8 @@ impl From for usize { impl ItemId { /// Get a numeric representation of this ID. - pub(crate) fn as_usize(&self) -> usize { - (*self).into() + pub(crate) fn as_usize(self) -> usize { + self.into() } } @@ -308,7 +308,7 @@ enum TypeKey { /// A context used during parsing and generation of structs. #[derive(Debug)] pub(crate) struct BindgenContext { - /// The map of all the items parsed so far, keyed off ItemId. + /// The map of all the items parsed so far, keyed off `ItemId`. items: Vec>, /// Clang USR to type map. This is needed to be able to associate types with @@ -317,7 +317,7 @@ pub(crate) struct BindgenContext { /// Maps from a cursor to the item ID of the named template type parameter /// for that cursor. - type_params: HashMap, + type_params: HashMap, /// A cursor to module map. Similar reason than above. modules: HashMap, @@ -328,13 +328,13 @@ pub(crate) struct BindgenContext { /// Current module being traversed. current_module: ModuleId, - /// A HashMap keyed on a type definition, and whose value is the parent ID + /// A `HashMap` keyed on a type definition, and whose value is the parent ID /// of the declaration. /// /// This is used to handle the cases where the semantic and the lexical /// parents of the cursor differ, like when a nested class is defined /// outside of the parent class. - semantic_parents: HashMap, + semantic_parents: HashMap, /// A stack with the current type declarations and types we're parsing. This /// is needed to avoid infinite recursion when parsing a type like: @@ -344,7 +344,7 @@ pub(crate) struct BindgenContext { /// This means effectively, that a type has a potential ID before knowing if /// it's a correct type. But that's not important in practice. /// - /// We could also use the `types` HashMap, but my intention with it is that + /// We could also use the `types` `HashMap`, but my intention with it is that /// only valid types and declarations end up there, and this could /// potentially break that assumption. currently_parsed_types: Vec, @@ -353,7 +353,7 @@ pub(crate) struct BindgenContext { /// hard errors while parsing duplicated macros, as well to allow macro /// expression parsing. /// - /// This needs to be an std::HashMap because the cexpr API requires it. + /// This needs to be an `std::HashMap` because the `cexpr` API requires it. parsed_macros: StdHashMap, cexpr::expr::EvalResult>, /// A map with all include locations. @@ -377,12 +377,18 @@ pub(crate) struct BindgenContext { /// The translation unit for parsing. translation_unit: clang::TranslationUnit, + /// The translation unit for macro fallback parsing. + fallback_tu: Option, + /// Target information that can be useful for some stuff. target_info: clang::TargetInfo, /// The options given by the user via cli or other medium. options: BindgenOptions, + /// Whether an opaque array was generated + generated_opaque_array: Cell, + /// Whether a bindgen complex was generated generated_bindgen_complex: Cell, @@ -496,7 +502,7 @@ struct AllowlistedItemsTraversal<'ctx> { traversal: ItemTraversal<'ctx, ItemSet, Vec>, } -impl<'ctx> Iterator for AllowlistedItemsTraversal<'ctx> { +impl Iterator for AllowlistedItemsTraversal<'_> { type Item = ItemId; fn next(&mut self) -> Option { @@ -585,10 +591,12 @@ If you encounter an error missing from this list, please file an issue or a PR!" collected_typerefs: false, in_codegen: false, translation_unit, + fallback_tu: None, target_info, options, generated_bindgen_complex: Cell::new(false), generated_bindgen_float16: Cell::new(false), + generated_opaque_array: Cell::new(false), allowlisted: None, blocklisted_types_implement_traits: Default::default(), codegen_items: None, @@ -613,7 +621,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" self.target_info.triple.starts_with("wasm32-") } - /// Creates a timer for the current bindgen phase. If time_phases is `true`, + /// Creates a timer for the current bindgen phase. If `time_phases` is `true`, /// the timer will print to stderr when it is dropped, otherwise it will do /// nothing. pub(crate) fn timer<'a>(&self, name: &'a str) -> Timer<'a> { @@ -692,10 +700,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" declaration: Option, location: Option, ) { - debug!( - "BindgenContext::add_item({:?}, declaration: {:?}, loc: {:?}", - item, declaration, location - ); + debug!("BindgenContext::add_item({item:?}, declaration: {declaration:?}, loc: {location:?}"); debug_assert!( declaration.is_some() || !item.kind().is_type() || @@ -747,8 +752,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" // Fortunately, we don't care about those types being // duplicated, so we can just ignore them. debug!( - "Invalid declaration {:?} found for type {:?}", - declaration, + "Invalid declaration {declaration:?} found for type {:?}", self.resolve_item_fallible(id) .unwrap() .kind() @@ -762,10 +766,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } else if let Some(usr) = declaration.usr() { TypeKey::Usr(usr) } else { - warn!( - "Valid declaration with no USR: {:?}, {:?}", - declaration, location - ); + warn!("Valid declaration with no USR: {declaration:?}, {location:?}"); TypeKey::Declaration(declaration) }; @@ -779,7 +780,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// codegen'd, even if its parent is not allowlisted. See issue #769 for /// details. fn add_item_to_module(&mut self, item: &Item) { - assert!(item.id() != self.root_module); + assert_ne!(item.id(), self.root_module); assert!(self.resolve_item_fallible(item.id()).is_none()); if let Some(ref mut parent) = self.items[item.parent_id().0] { @@ -801,7 +802,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" self.current_module ); - self.items[(self.current_module.0).0] + self.items[self.current_module.0 .0] .as_mut() .expect("Should always have an item for self.current_module") .as_module_mut() @@ -811,15 +812,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Add a new named template type parameter to this context's item set. - pub(crate) fn add_type_param( - &mut self, - item: Item, - definition: clang::Cursor, - ) { - debug!( - "BindgenContext::add_type_param: item = {:?}; definition = {:?}", - item, definition - ); + pub(crate) fn add_type_param(&mut self, item: Item, definition: Cursor) { + debug!("BindgenContext::add_type_param: item = {item:?}; definition = {definition:?}"); assert!( item.expect_type().is_type_param(), @@ -850,15 +844,12 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Get the named type defined at the given cursor location, if we've /// already added one. - pub(crate) fn get_type_param( - &self, - definition: &clang::Cursor, - ) -> Option { + pub(crate) fn get_type_param(&self, definition: &Cursor) -> Option { assert_eq!( definition.kind(), clang_sys::CXCursor_TemplateTypeParameter ); - self.type_params.get(definition).cloned() + self.type_params.get(definition).copied() } // TODO: Move all this syntax crap to other part of the code. @@ -874,7 +865,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" "abstract" | "alignof" | "as" | "async" | "await" | "become" | "box" | "break" | "const" | "continue" | "crate" | "do" | "dyn" | "else" | "enum" | "extern" | "false" | "final" | - "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | + "fn" | "for" | "gen" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match" | "mod" | "move" | "mut" | "offsetof" | "override" | "priv" | "proc" | "pub" | "pure" | "ref" | "return" | "Self" | "self" | "sizeof" | "static" | @@ -927,23 +918,20 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Gather all the unresolved type references. fn collect_typerefs( &mut self, - ) -> Vec<(ItemId, clang::Type, clang::Cursor, Option)> { + ) -> Vec<(ItemId, clang::Type, Cursor, Option)> { debug_assert!(!self.collected_typerefs); self.collected_typerefs = true; let mut typerefs = vec![]; for (id, item) in self.items() { let kind = item.kind(); - let ty = match kind.as_type() { - Some(ty) => ty, - None => continue, - }; + let Some(ty) = kind.as_type() else { continue }; if let TypeKind::UnresolvedTypeRef(ref ty, loc, parent_id) = *ty.kind() { typerefs.push((id, *ty, loc, parent_id)); - }; + } } typerefs } @@ -1074,9 +1062,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" // Calls to `canonical_name` are expensive, so eagerly filter out // items that cannot be replaced. - let ty = match item.kind().as_type() { - Some(ty) => ty, - None => continue, + let Some(ty) = item.kind().as_type() else { + continue; }; match *ty.kind() { @@ -1105,7 +1092,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } for (id, replacement_id) in replacements { - debug!("Replacing {:?} with {:?}", id, replacement_id); + debug!("Replacing {id:?} with {replacement_id:?}"); let new_parent = { let item_id: ItemId = id.into(); let item = self.items[item_id.0].as_mut().unwrap(); @@ -1142,7 +1129,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" .chain(Some(immut_self.root_module.into())) .find(|id| { let item = immut_self.resolve_item(*id); - item.as_module().map_or(false, |m| { + item.as_module().is_some_and(|m| { m.children().contains(&replacement_id.into()) }) }) @@ -1230,7 +1217,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// When the `__testing_only_extra_assertions` feature is enabled, this /// function walks the IR graph and asserts that we do not have any edges - /// referencing an ItemId for which we do not have an associated IR item. + /// referencing an `ItemId` for which we do not have an associated IR item. fn assert_no_dangling_references(&self) { if cfg!(feature = "__testing_only_extra_assertions") { for _ in self.assert_no_dangling_item_traversal() { @@ -1243,7 +1230,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" &self, ) -> traversal::AssertNoDanglingItemsTraversal { assert!(self.in_codegen_phase()); - assert!(self.current_module == self.root_module); + assert_eq!(self.current_module, self.root_module); let roots = self.items().map(|(id, _)| id); traversal::AssertNoDanglingItemsTraversal::new( @@ -1259,7 +1246,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" fn assert_every_item_in_a_module(&self) { if cfg!(feature = "__testing_only_extra_assertions") { assert!(self.in_codegen_phase()); - assert!(self.current_module == self.root_module); + assert_eq!(self.current_module, self.root_module); for (id, _item) in self.items() { if id == self.root_module { @@ -1277,19 +1264,13 @@ If you encounter an error missing from this list, please file an issue or a PR!" id.ancestors(self) .chain(Some(self.root_module.into())) .any(|ancestor| { - debug!( - "Checking if {:?} is a child of {:?}", - id, ancestor - ); + debug!("Checking if {id:?} is a child of {ancestor:?}"); self.resolve_item(ancestor) .as_module() - .map_or(false, |m| { - m.children().contains(&id) - }) + .is_some_and(|m| m.children().contains(&id)) }) }, - "{:?} should be in some ancestor module's children set", - id + "{id:?} should be in some ancestor module's children set" ); } } @@ -1314,7 +1295,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" .as_ref() .unwrap() .get(&id) - .cloned() + .copied() .unwrap_or(SizednessResult::ZeroSized) } @@ -1338,7 +1319,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" .as_ref() .unwrap() .get(&id.into()) - .cloned() + .copied() .unwrap_or(HasVtableResult::No) } @@ -1418,8 +1399,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" self.used_template_parameters .as_ref() .expect("should have found template parameter usage if we're in codegen") - .get(&item) - .map_or(false, |items_used_params| items_used_params.contains(&template_param)) + .get(&item).is_some_and(|items_used_params| items_used_params.contains(&template_param)) } /// Return `true` if `item` uses any unbound, generic template parameters, @@ -1438,7 +1418,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" "should have template parameter usage info in codegen phase", ) .get(&item) - .map_or(false, |used| !used.is_empty()) + .is_some_and(|used| !used.is_empty()) } // This deserves a comment. Builtin types don't get a valid declaration, so @@ -1450,7 +1430,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" // If at some point we care about the memory here, probably a map TypeKind // -> builtin type ItemId would be the best to improve that. fn add_builtin_item(&mut self, item: Item) { - debug!("add_builtin_item: item = {:?}", item); + debug!("add_builtin_item: item = {item:?}"); debug_assert!(item.kind().is_type()); self.add_item_to_module(&item); let id = item.id(); @@ -1509,7 +1489,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" let item_id = item_id.into(); match self.resolve_item_fallible(item_id) { Some(item) => item, - None => panic!("Not an item: {:?}", item_id), + None => panic!("Not an item: {item_id:?}"), } } @@ -1524,11 +1504,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// correct type definition afterwards. /// /// TODO(emilio): We could consider doing this only when - /// declaration.lexical_parent() != definition.lexical_parent(), but it's + /// `declaration.lexical_parent() != definition.lexical_parent()`, but it's /// not sure it's worth it. pub(crate) fn add_semantic_parent( &mut self, - definition: clang::Cursor, + definition: Cursor, parent_id: ItemId, ) { self.semantic_parents.insert(definition, parent_id); @@ -1537,9 +1517,9 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Returns a known semantic parent for a given definition. pub(crate) fn known_semantic_parent( &self, - definition: clang::Cursor, + definition: Cursor, ) -> Option { - self.semantic_parents.get(&definition).cloned() + self.semantic_parents.get(&definition).copied() } /// Given a cursor pointing to the location of a template instantiation, @@ -1587,7 +1567,6 @@ If you encounter an error missing from this list, please file an issue or a PR!" self.currently_parsed_types() .iter() .find(|partial_ty| *partial_ty.decl() == referenced) - .cloned() }) .and_then(|template_decl| { let num_template_params = @@ -1612,7 +1591,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// function template declarations(!?!??!). /// /// The only way to do this is manually inspecting the AST and looking for - /// TypeRefs and TemplateRefs inside. This, unfortunately, doesn't work for + /// `TypeRefs` and `TemplateRefs` inside. This, unfortunately, doesn't work for /// more complex cases, see the comment on the assertion below. /// /// To add insult to injury, the AST itself has structure that doesn't make @@ -1643,7 +1622,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" with_id: ItemId, template: TypeId, ty: &clang::Type, - location: clang::Cursor, + location: Cursor, ) -> Option { let num_expected_args = self.resolve_type(template).num_self_template_params(self); @@ -1787,8 +1766,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } _ => { warn!( - "Found template arg cursor we can't handle: {:?}", - child + "Found template arg cursor we can't handle: {child:?}" ); found_const_arg = true; } @@ -1839,7 +1817,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" ); // Bypass all the validations in add_item explicitly. - debug!("instantiate_template: inserting item: {:?}", item); + debug!("instantiate_template: inserting item: {item:?}"); self.add_item_to_module(&item); debug_assert_eq!(with_id, item.id()); self.items[with_id.0] = Some(item); @@ -1859,7 +1837,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" .usr() .and_then(|usr| self.types.get(&TypeKey::Usr(usr))) }) - .cloned() + .copied() } /// Looks up for an already resolved type, either because it's builtin, or @@ -1869,19 +1847,15 @@ If you encounter an error missing from this list, please file an issue or a PR!" with_id: ItemId, parent_id: Option, ty: &clang::Type, - location: Option, + location: Option, ) -> Option { use clang_sys::{CXCursor_TypeAliasTemplateDecl, CXCursor_TypeRef}; - debug!( - "builtin_or_resolved_ty: {:?}, {:?}, {:?}, {:?}", - ty, location, with_id, parent_id - ); + debug!("builtin_or_resolved_ty: {ty:?}, {location:?}, {with_id:?}, {parent_id:?}"); if let Some(decl) = ty.canonical_declaration(location.as_ref()) { if let Some(id) = self.get_resolved_type(&decl) { debug!( - "Already resolved ty {:?}, {:?}, {:?} {:?}", - id, decl, ty, location + "Already resolved ty {id:?}, {decl:?}, {ty:?} {location:?}" ); // If the declaration already exists, then either: // @@ -2006,6 +1980,9 @@ If you encounter an error missing from this list, please file an issue or a PR!" CXType_Short => TypeKind::Int(IntKind::Short), CXType_UShort => TypeKind::Int(IntKind::UShort), CXType_WChar => TypeKind::Int(IntKind::WChar), + CXType_Char16 if self.options().use_distinct_char16_t => { + TypeKind::Int(IntKind::Char16) + } CXType_Char16 => TypeKind::Int(IntKind::U16), CXType_Char32 => TypeKind::Int(IntKind::U32), CXType_Long => TypeKind::Int(IntKind::Long), @@ -2029,8 +2006,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" CXType_LongDouble => FloatKind::LongDouble, CXType_Float128 => FloatKind::Float128, _ => panic!( - "Non floating-type complex? {:?}, {:?}", - ty, float_type, + "Non floating-type complex? {ty:?}, {float_type:?}", ), }; TypeKind::Complex(float_kind) @@ -2061,6 +2037,93 @@ If you encounter an error missing from this list, please file an issue or a PR!" &self.translation_unit } + /// Initialize fallback translation unit if it does not exist and + /// then return a mutable reference to the fallback translation unit. + pub(crate) fn try_ensure_fallback_translation_unit( + &mut self, + ) -> Option<&mut clang::FallbackTranslationUnit> { + if self.fallback_tu.is_none() { + let file = format!( + "{}/.macro_eval.c", + match self.options().clang_macro_fallback_build_dir { + Some(ref path) => path.as_os_str().to_str()?, + None => ".", + } + ); + + let index = clang::Index::new(false, false); + + let mut header_names_to_compile = Vec::new(); + let mut header_paths = Vec::new(); + let mut header_includes = Vec::new(); + let single_header = self.options().input_headers.last().cloned()?; + for input_header in &self.options.input_headers + [..self.options.input_headers.len() - 1] + { + let path = Path::new(input_header.as_ref()); + if let Some(header_path) = path.parent() { + if header_path == Path::new("") { + header_paths.push("."); + } else { + header_paths.push(header_path.as_os_str().to_str()?); + } + } else { + header_paths.push("."); + } + let header_name = path.file_name()?.to_str()?; + header_includes.push(header_name.to_string()); + header_names_to_compile + .push(header_name.split(".h").next()?.to_string()); + } + let pch = format!( + "{}/{}", + match self.options().clang_macro_fallback_build_dir { + Some(ref path) => path.as_os_str().to_str()?, + None => ".", + }, + header_names_to_compile.join("-") + "-precompile.h.pch" + ); + + let mut c_args = self.options.fallback_clang_args.clone(); + c_args.push("-x".to_string().into_boxed_str()); + c_args.push("c-header".to_string().into_boxed_str()); + for header_path in header_paths { + c_args.push(format!("-I{header_path}").into_boxed_str()); + } + for header_include in header_includes { + c_args.push("-include".to_string().into_boxed_str()); + c_args.push(header_include.into_boxed_str()); + } + let mut tu = clang::TranslationUnit::parse( + &index, + &single_header, + &c_args, + &[], + clang_sys::CXTranslationUnit_ForSerialization, + )?; + tu.save(&pch).ok()?; + + let mut c_args = vec![ + "-include-pch".to_string().into_boxed_str(), + pch.clone().into_boxed_str(), + ]; + let mut skip_next = false; + for arg in &self.options.fallback_clang_args { + if arg.as_ref() == "-include" { + skip_next = true; + } else if skip_next { + skip_next = false; + } else { + c_args.push(arg.clone()); + } + } + self.fallback_tu = + Some(clang::FallbackTranslationUnit::new(file, pch, &c_args)?); + } + + self.fallback_tu.as_mut() + } + /// Have we parsed the macro named `macro_name` already? pub(crate) fn parsed_macro(&self, macro_name: &[u8]) -> bool { self.parsed_macros.contains_key(macro_name) @@ -2096,19 +2159,14 @@ If you encounter an error missing from this list, please file an issue or a PR!" pub(crate) fn replace(&mut self, name: &[String], potential_ty: ItemId) { match self.replacements.entry(name.into()) { Entry::Vacant(entry) => { - debug!( - "Defining replacement for {:?} as {:?}", - name, potential_ty - ); + debug!("Defining replacement for {name:?} as {potential_ty:?}"); entry.insert(potential_ty); } Entry::Occupied(occupied) => { warn!( - "Replacement for {:?} already defined as {:?}; \ - ignoring duplicate replacement definition as {:?}", - name, + "Replacement for {name:?} already defined as {:?}; \ + ignoring duplicate replacement definition as {potential_ty:?}", occupied.get(), - potential_ty ); } } @@ -2143,7 +2201,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// namespace. fn tokenize_namespace( &self, - cursor: &clang::Cursor, + cursor: &Cursor, ) -> (Option, ModuleKind) { assert_eq!( cursor.kind(), @@ -2154,7 +2212,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" let mut module_name = None; let spelling = cursor.spelling(); if !spelling.is_empty() { - module_name = Some(spelling) + module_name = Some(spelling); } let mut kind = ModuleKind::Normal; @@ -2194,33 +2252,31 @@ If you encounter an error missing from this list, please file an issue or a PR!" ); } break; - } else { - // This is _likely_, but not certainly, a macro that's - // been placed just before the namespace keyword. - // Unfortunately, clang tokens don't let us easily see - // through the ifdef tokens, so we don't know what this - // token should really be. Instead of panicking though, - // we warn the user that we assumed the token was blank, - // and then move on. - // - // See also https://github.com/rust-lang/rust-bindgen/issues/1676. - warn!( - "Ignored unknown namespace prefix '{}' at {:?} in {:?}", - String::from_utf8_lossy(name), - token, - cursor - ); } + // This is _likely_, but not certainly, a macro that's + // been placed just before the namespace keyword. + // Unfortunately, clang tokens don't let us easily see + // through the ifdef tokens, so we don't know what this + // token should really be. Instead of panicking though, + // we warn the user that we assumed the token was blank, + // and then move on. + // + // See also https://github.com/rust-lang/rust-bindgen/issues/1676. + warn!("Ignored unknown namespace prefix '{}' at {token:?} in {cursor:?}", String::from_utf8_lossy(name)); } } } + if cursor.is_inline_namespace() { + kind = ModuleKind::Inline; + } + (module_name, kind) } - /// Given a CXCursor_Namespace cursor, return the item ID of the + /// Given a `CXCursor_Namespace` cursor, return the item ID of the /// corresponding module, or create one on the fly. - pub(crate) fn module(&mut self, cursor: clang::Cursor) -> ModuleId { + pub(crate) fn module(&mut self, cursor: Cursor) -> ModuleId { use clang_sys::*; assert_eq!(cursor.kind(), CXCursor_Namespace, "Be a nice person"); let cursor = cursor.canonical(); @@ -2271,7 +2327,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// allowlisted. pub(crate) fn allowlisted_items(&self) -> &ItemSet { assert!(self.in_codegen_phase()); - assert!(self.current_module == self.root_module); + assert_eq!(self.current_module, self.root_module); self.allowlisted.as_ref().unwrap() } @@ -2284,7 +2340,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" derive_trait: DeriveTrait, ) -> CanDerive { assert!(self.in_codegen_phase()); - assert!(self.current_module == self.root_module); + assert_eq!(self.current_module, self.root_module); *self .blocklisted_types_implement_traits @@ -2332,14 +2388,14 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Get a reference to the set of items we should generate. pub(crate) fn codegen_items(&self) -> &ItemSet { assert!(self.in_codegen_phase()); - assert!(self.current_module == self.root_module); + assert_eq!(self.current_module, self.root_module); self.codegen_items.as_ref().unwrap() } /// Compute the allowlisted items set and populate `self.allowlisted`. fn compute_allowlisted_and_codegen_items(&mut self) { assert!(self.in_codegen_phase()); - assert!(self.current_module == self.root_module); + assert_eq!(self.current_module, self.root_module); assert!(self.allowlisted.is_none()); let _t = self.timer("compute_allowlisted_and_codegen_items"); @@ -2384,7 +2440,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } let name = item.path_for_allowlisting(self)[1..].join("::"); - debug!("allowlisted_items: testing {:?}", name); + debug!("allowlisted_items: testing {name:?}"); if self.options().allowlisted_items.matches(&name) { return true; @@ -2438,9 +2494,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" return false; } - let enum_ = match *ty.kind() { - TypeKind::Enum(ref e) => e, - _ => return false, + let TypeKind::Enum(ref enum_) = *ty.kind() else { + return false; }; if ty.name().is_some() { @@ -2455,7 +2510,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" ); let name = prefix_path[1..].join("::"); prefix_path.pop().unwrap(); - self.options().allowlisted_vars.matches(name) + self.options().allowlisted_vars.matches(&name) + || self + .options() + .allowlisted_items + .matches(name) }) } } @@ -2529,9 +2588,19 @@ If you encounter an error missing from this list, please file an issue or a PR!" } } + /// Call if an opaque array is generated + pub(crate) fn generated_opaque_array(&self) { + self.generated_opaque_array.set(true); + } + + /// Whether we need to generate the opaque array type + pub(crate) fn need_opaque_array_type(&self) -> bool { + self.generated_opaque_array.get() + } + /// Call if a bindgen complex is generated pub(crate) fn generated_bindgen_complex(&self) { - self.generated_bindgen_complex.set(true) + self.generated_bindgen_complex.set(true); } /// Whether we need to generate the bindgen complex type @@ -2541,7 +2610,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Call if a bindgen float16 is generated pub(crate) fn generated_bindgen_float16(&self) { - self.generated_bindgen_float16.set(true) + self.generated_bindgen_float16.set(true); } /// Whether we need to generate the bindgen float16 type @@ -2714,7 +2783,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" !self.cannot_derive_hash.as_ref().unwrap().contains(&id) } - /// Compute whether we can derive PartialOrd, PartialEq or Eq. + /// Compute whether we can derive `PartialOrd`, `PartialEq` or `Eq`. fn compute_cannot_derive_partialord_partialeq_or_eq(&mut self) { let _t = self.timer("compute_cannot_derive_partialord_partialeq_or_eq"); assert!(self.cannot_derive_partialeq_or_partialord.is_none()); @@ -2749,7 +2818,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" .as_ref() .unwrap() .get(&id) - .cloned() + .copied() .unwrap_or(CanDerive::Yes) } @@ -3007,7 +3076,7 @@ impl TemplateParameters for PartialType { num_params += 1; } _ => {} - }; + } clang_sys::CXChildVisit_Continue }); num_params @@ -3018,7 +3087,7 @@ impl TemplateParameters for PartialType { } fn unused_regex_diagnostic(item: &str, name: &str, _ctx: &BindgenContext) { - warn!("unused option: {} {}", name, item); + warn!("unused option: {name} {item}"); #[cfg(feature = "experimental")] if _ctx.options().emit_diagnostics { @@ -3026,11 +3095,11 @@ fn unused_regex_diagnostic(item: &str, name: &str, _ctx: &BindgenContext) { Diagnostic::default() .with_title( - format!("Unused regular expression: `{}`.", item), - Level::Warn, + format!("Unused regular expression: `{item}`."), + Level::Warning, ) .add_annotation( - format!("This regular expression was passed to `{}`.", name), + format!("This regular expression was passed to `{name}`."), Level::Note, ) .display(); diff --git a/bindgen/ir/derive.rs b/bindgen/ir/derive.rs index 3877b42f8f..3ee6476af9 100644 --- a/bindgen/ir/derive.rs +++ b/bindgen/ir/derive.rs @@ -3,10 +3,10 @@ //! These traits tend to come in pairs: //! //! 1. A "trivial" version, whose implementations aren't allowed to recursively -//! look at other types or the results of fix point analyses. +//! look at other types or the results of fix point analyses. //! //! 2. A "normal" version, whose implementations simply query the results of a -//! fix point analysis. +//! fix point analysis. //! //! The former is used by the analyses when creating the results queried by the //! second. @@ -92,9 +92,10 @@ pub(crate) trait CanDeriveOrd { /// /// Initially we assume that we can derive trait for all types and then /// update our understanding as we learn more about each type. -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] pub enum CanDerive { /// Yes, we can derive automatically. + #[default] Yes, /// The only thing that stops us from automatically deriving is that @@ -107,12 +108,6 @@ pub enum CanDerive { No, } -impl Default for CanDerive { - fn default() -> CanDerive { - CanDerive::Yes - } -} - impl CanDerive { /// Take the least upper bound of `self` and `rhs`. pub(crate) fn join(self, rhs: Self) -> Self { @@ -130,6 +125,6 @@ impl ops::BitOr for CanDerive { impl ops::BitOrAssign for CanDerive { fn bitor_assign(&mut self, rhs: Self) { - *self = self.join(rhs) + *self = self.join(rhs); } } diff --git a/bindgen/ir/dot.rs b/bindgen/ir/dot.rs index d5c1a42fdc..9bfc559f41 100644 --- a/bindgen/ir/dot.rs +++ b/bindgen/ir/dot.rs @@ -17,7 +17,7 @@ pub(crate) trait DotAttributes { out: &mut W, ) -> io::Result<()> where - W: io::Write; + W: Write; } /// Write a graphviz dot file containing our IR. @@ -41,7 +41,7 @@ where if is_allowlisted { "black" } else { "gray" } )?; item.dot_attributes(ctx, &mut dot_file)?; - writeln!(&mut dot_file, r#" >];"#)?; + writeln!(&mut dot_file, " >];")?; item.trace( ctx, @@ -52,10 +52,9 @@ where match writeln!( &mut dot_file, - "{} -> {} [label={:?}, color={}];", + "{} -> {} [label={edge_kind:?}, color={}];", id.as_usize(), sub_id.as_usize(), - edge_kind, if is_allowlisted { "black" } else { "gray" } ) { Ok(_) => {} diff --git a/bindgen/ir/enum_ty.rs b/bindgen/ir/enum_ty.rs index 70cf0eae88..9b08da3bce 100644 --- a/bindgen/ir/enum_ty.rs +++ b/bindgen/ir/enum_ty.rs @@ -59,7 +59,7 @@ impl Enum { ctx: &mut BindgenContext, ) -> Result { use clang_sys::*; - debug!("Enum::from_ty {:?}", ty); + debug!("Enum::from_ty {ty:?}"); if ty.kind() != CXType_Enum { return Err(ParseError::Continue); @@ -73,13 +73,13 @@ impl Enum { let variant_ty = repr.and_then(|r| ctx.resolve_type(r).safe_canonical_type(ctx)); - let is_bool = variant_ty.map_or(false, Type::is_bool); + let is_bool = variant_ty.is_some_and(Type::is_bool); // Assume signedness since the default type by the C standard is an int. let is_signed = variant_ty.map_or(true, |ty| match *ty.kind() { TypeKind::Int(ref int_kind) => int_kind.is_signed(), ref other => { - panic!("Since when enums can be non-integers? {:?}", other) + panic!("Since when enums can be non-integers? {other:?}") } }); @@ -310,14 +310,12 @@ impl EnumVariant { /// Returns whether this variant should be enforced to be a constant by code /// generation. pub(crate) fn force_constification(&self) -> bool { - self.custom_behavior - .map_or(false, |b| b == EnumVariantCustomBehavior::Constify) + self.custom_behavior == Some(EnumVariantCustomBehavior::Constify) } /// Returns whether the current variant should be hidden completely from the /// resulting rust enum. pub(crate) fn hidden(&self) -> bool { - self.custom_behavior - .map_or(false, |b| b == EnumVariantCustomBehavior::Hide) + self.custom_behavior == Some(EnumVariantCustomBehavior::Hide) } } diff --git a/bindgen/ir/function.rs b/bindgen/ir/function.rs index 448bcd22ea..65a12d4bb2 100644 --- a/bindgen/ir/function.rs +++ b/bindgen/ir/function.rs @@ -9,7 +9,7 @@ use super::ty::TypeKind; use crate::callbacks::{ItemInfo, ItemKind}; use crate::clang::{self, ABIKind, Attribute}; use crate::parse::{ClangSubItemParser, ParseError, ParseResult}; -use clang_sys::{self, CXCallingConv}; +use clang_sys::CXCallingConv; use quote::TokenStreamExt; use std::io; @@ -17,7 +17,7 @@ use std::str::FromStr; const RUST_DERIVE_FUNPTR_LIMIT: usize = 12; -/// What kind of a function are we looking at? +/// What kind of function are we looking at? #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) enum FunctionKind { /// A plain, free function. @@ -82,7 +82,7 @@ pub(crate) struct Function { /// The mangled name, that is, the symbol. mangled_name: Option, - /// The link name. If specified, overwrite mangled_name. + /// The link name. If specified, overwrite `mangled_name`. link_name: Option, /// The ID pointing to the current function signature. @@ -158,11 +158,7 @@ impl DotAttributes for Function { if let Some(ref mangled) = self.mangled_name { let mangled: String = mangled.chars().flat_map(|c| c.escape_default()).collect(); - writeln!( - out, - "mangled name{}", - mangled - )?; + writeln!(out, "mangled name{mangled}")?; } Ok(()) @@ -209,7 +205,7 @@ impl FromStr for Abi { "win64" => Ok(Self::Win64), "C-unwind" => Ok(Self::CUnwind), "system" => Ok(Self::System), - _ => Err(format!("Invalid or unknown ABI {:?}", s)), + _ => Err(format!("Invalid or unknown ABI {s:?}")), } } } @@ -251,8 +247,8 @@ pub(crate) enum ClangAbi { impl ClangAbi { /// Returns whether this Abi is known or not. - fn is_unknown(&self) -> bool { - matches!(*self, ClangAbi::Unknown(..)) + fn is_unknown(self) -> bool { + matches!(self, ClangAbi::Unknown(..)) } } @@ -261,8 +257,7 @@ impl quote::ToTokens for ClangAbi { match *self { Self::Known(abi) => abi.to_tokens(tokens), Self::Unknown(cc) => panic!( - "Cannot turn unknown calling convention to tokens: {:?}", - cc + "Cannot turn unknown calling convention to tokens: {cc:?}" ), } } @@ -295,15 +290,15 @@ pub(crate) struct FunctionSig { fn get_abi(cc: CXCallingConv) -> ClangAbi { use clang_sys::*; match cc { - CXCallingConv_Default => ClangAbi::Known(Abi::C), - CXCallingConv_C => ClangAbi::Known(Abi::C), + CXCallingConv_Default | CXCallingConv_C => ClangAbi::Known(Abi::C), CXCallingConv_X86StdCall => ClangAbi::Known(Abi::Stdcall), CXCallingConv_X86FastCall => ClangAbi::Known(Abi::Fastcall), CXCallingConv_X86ThisCall => ClangAbi::Known(Abi::ThisCall), - CXCallingConv_X86VectorCall => ClangAbi::Known(Abi::Vectorcall), + CXCallingConv_X86VectorCall | CXCallingConv_AArch64VectorCall => { + ClangAbi::Known(Abi::Vectorcall) + } CXCallingConv_AAPCS => ClangAbi::Known(Abi::Aapcs), CXCallingConv_X86_64Win64 => ClangAbi::Known(Abi::Win64), - CXCallingConv_AArch64VectorCall => ClangAbi::Known(Abi::Vectorcall), other => ClangAbi::Unknown(other), } } @@ -423,7 +418,7 @@ impl FunctionSig { ctx: &mut BindgenContext, ) -> Result { use clang_sys::*; - debug!("FunctionSig::from_ty {:?} {:?}", ty, cursor); + debug!("FunctionSig::from_ty {ty:?} {cursor:?}"); // Skip function templates let kind = cursor.kind(); @@ -438,7 +433,7 @@ impl FunctionSig { spelling.starts_with("operator") && !clang::is_valid_identifier(spelling) }; - if is_operator(&spelling) { + if is_operator(&spelling) && !ctx.options().represent_cxx_operators { return Err(ParseError::Continue); } @@ -538,7 +533,10 @@ impl FunctionSig { let is_const = is_method && cursor.method_is_const(); let is_virtual = is_method && cursor.method_is_virtual(); let is_static = is_method && cursor.method_is_static(); - if !is_static && !is_virtual { + if !is_static && + (!is_virtual || + ctx.options().use_specific_virtual_function_receiver) + { let parent = cursor.semantic_parent(); let class = Item::parse(parent, None, ctx) .expect("Expected to parse the class"); @@ -601,7 +599,7 @@ impl FunctionSig { let abi = get_abi(call_conv); if abi.is_unknown() { - warn!("Unknown calling convention: {:?}", call_conv); + warn!("Unknown calling convention: {call_conv:?}"); } Ok(Self { @@ -731,13 +729,14 @@ impl ClangSubItemParser for Function { Some(k) => k, }; - debug!("Function::parse({:?}, {:?})", cursor, cursor.cur_type()); + debug!("Function::parse({cursor:?}, {:?})", cursor.cur_type()); let visibility = cursor.visibility(); if visibility != CXVisibility_Default { return Err(ParseError::Continue); } - - if cursor.access_specifier() == CX_CXXPrivate { + if cursor.access_specifier() == CX_CXXPrivate && + !context.options().generate_private_functions + { return Err(ParseError::Continue); } @@ -749,9 +748,7 @@ impl ClangSubItemParser for Function { }; if cursor.is_inlined_function() || - cursor - .definition() - .map_or(false, |x| x.is_inlined_function()) + cursor.definition().is_some_and(|x| x.is_inlined_function()) { if !context.options().generate_inline_functions && !context.options().wrap_static_fns @@ -759,7 +756,9 @@ impl ClangSubItemParser for Function { return Err(ParseError::Continue); } - if cursor.is_deleted_function() { + if cursor.is_deleted_function() && + !context.options().generate_deleted_functions + { return Err(ParseError::Continue); } diff --git a/bindgen/ir/int.rs b/bindgen/ir/int.rs index 4251b3753a..ed18a99949 100644 --- a/bindgen/ir/int.rs +++ b/bindgen/ir/int.rs @@ -54,9 +54,12 @@ pub enum IntKind { /// A 16-bit signed integer. I16, - /// Either a `char16_t` or a `wchar_t`. + /// A 16-bit integer, used only for enum size representation. U16, + /// The C++ type `char16_t`, which is its own type (unlike in C). + Char16, + /// A 32-bit signed integer. I32, @@ -94,14 +97,12 @@ impl IntKind { // to know whether it is or not right now (unlike char, there's no // WChar_S / WChar_U). Bool | UChar | UShort | UInt | ULong | ULongLong | U8 | U16 | - WChar | U32 | U64 | U128 => false, + Char16 | WChar | U32 | U64 | U128 => false, SChar | Short | Int | Long | LongLong | I8 | I16 | I32 | I64 | I128 => true, - Char { is_signed } => is_signed, - - Custom { is_signed, .. } => is_signed, + Char { is_signed } | Custom { is_signed, .. } => is_signed, } } @@ -112,7 +113,7 @@ impl IntKind { use self::IntKind::*; Some(match *self { Bool | UChar | SChar | U8 | I8 | Char { .. } => 1, - U16 | I16 => 2, + U16 | I16 | Char16 => 2, U32 | I32 => 4, U64 | I64 => 8, I128 | U128 => 16, diff --git a/bindgen/ir/item.rs b/bindgen/ir/item.rs index 4eb9ef8bf4..25c3c258aa 100644 --- a/bindgen/ir/item.rs +++ b/bindgen/ir/item.rs @@ -20,13 +20,12 @@ use super::ty::{Type, TypeKind}; use crate::clang; use crate::parse::{ClangSubItemParser, ParseError, ParseResult}; -use lazycell::LazyCell; - -use std::cell::Cell; +use std::cell::{Cell, OnceCell}; use std::collections::BTreeSet; use std::fmt::Write; use std::io; use std::iter; +use std::sync::OnceLock; /// A trait to get the canonical name from an item. /// @@ -45,7 +44,7 @@ pub(crate) trait ItemCanonicalName { /// The same, but specifies the path that needs to be followed to reach an item. /// -/// To contrast with canonical_name, here's an example: +/// To contrast with `canonical_name`, here's an example: /// /// ```c++ /// namespace foo { @@ -104,6 +103,7 @@ impl DebugOnlyItemSet { DebugOnlyItemSet } + #[allow(clippy::trivially_copy_pass_by_ref)] fn contains(&self, _id: &ItemId) -> bool { false } @@ -128,7 +128,7 @@ impl<'a> ItemAncestorsIter<'a> { } } -impl<'a> Iterator for ItemAncestorsIter<'a> { +impl Iterator for ItemAncestorsIter<'_> { type Item = ItemId; fn next(&mut self) -> Option { @@ -376,11 +376,11 @@ pub(crate) struct Item { /// The item's local ID, unique only amongst its siblings. Only used for /// anonymous items. /// - /// Lazily initialized in local_id(). + /// Lazily initialized in `local_id()`. /// /// Note that only structs, unions, and enums get a local type ID. In any /// case this is an implementation detail. - local_id: LazyCell, + local_id: OnceCell, /// The next local ID to use for a child or template instantiation. next_child_local_id: Cell, @@ -389,11 +389,11 @@ pub(crate) struct Item { /// /// This is a fairly used operation during codegen so this makes bindgen /// considerably faster in those cases. - canonical_name: LazyCell, + canonical_name: OnceCell, /// The path to use for allowlisting and other name-based checks, as /// returned by `path_for_allowlisting`, lazily constructed. - path_for_allowlisting: LazyCell>, + path_for_allowlisting: OnceCell>, /// A doc comment over the item, if any. comment: Option, @@ -431,10 +431,10 @@ impl Item { debug_assert!(id != parent_id || kind.is_module()); Item { id, - local_id: LazyCell::new(), + local_id: OnceCell::new(), next_child_local_id: Cell::new(1), - canonical_name: LazyCell::new(), - path_for_allowlisting: LazyCell::new(), + canonical_name: OnceCell::new(), + path_for_allowlisting: OnceCell::new(), parent_id, comment, annotations: annotations.unwrap_or_default(), @@ -493,7 +493,7 @@ impl Item { self.ancestors(ctx) .filter(|id| { - ctx.resolve_item(*id).as_module().map_or(false, |module| { + ctx.resolve_item(*id).as_module().is_some_and(|module| { !module.is_inline() || ctx.options().conservative_inline_namespaces }) @@ -535,7 +535,7 @@ impl Item { /// below this item's lexical scope, meaning that this can be useful for /// generating relatively stable identifiers within a scope. pub(crate) fn local_id(&self, ctx: &BindgenContext) -> usize { - *self.local_id.borrow_with(|| { + *self.local_id.get_or_init(|| { let parent = ctx.resolve_item(self.parent_id); parent.next_child_local_id() }) @@ -583,9 +583,8 @@ impl Item { let mut parent = self.parent_id; loop { - let parent_item = match ctx.resolve_item_fallible(parent) { - Some(item) => item, - None => return false, + let Some(parent_item) = ctx.resolve_item_fallible(parent) else { + return false; }; if parent_item.id() == ctx.root_module() { @@ -670,7 +669,7 @@ impl Item { } } - /// Take out item NameOptions + /// Take out item `NameOptions` pub(crate) fn name<'a>( &'a self, ctx: &'a BindgenContext, @@ -718,7 +717,7 @@ impl Item { s } - /// Helper function for full_disambiguated_name + /// Helper function for `full_disambiguated_name` fn push_disambiguated_name( &self, ctx: &BindgenContext, @@ -728,7 +727,7 @@ impl Item { to.push_str(&self.canonical_name(ctx)); if let ItemKind::Type(ref ty) = *self.kind() { if let TypeKind::TemplateInstantiation(ref inst) = *ty.kind() { - to.push_str(&format!("_open{}_", level)); + let _ = write!(to, "_open{level}_"); for arg in inst.template_arguments() { arg.into_resolver() .through_type_refs() @@ -736,7 +735,7 @@ impl Item { .push_disambiguated_name(ctx, to, level + 1); to.push('_'); } - to.push_str(&format!("close{}", level)); + let _ = write!(to, "close{level}"); } } } @@ -787,22 +786,20 @@ impl Item { match *self.kind() { ItemKind::Var(ref var) => var.name().to_owned(), - ItemKind::Module(ref module) => { - module.name().map(ToOwned::to_owned).unwrap_or_else(|| { - format!("_bindgen_mod_{}", self.exposed_id(ctx)) - }) - } - ItemKind::Type(ref ty) => { - ty.sanitized_name(ctx).map(Into::into).unwrap_or_else(|| { - format!("_bindgen_ty_{}", self.exposed_id(ctx)) - }) - } + ItemKind::Module(ref module) => module.name().map_or_else( + || format!("_bindgen_mod_{}", self.exposed_id(ctx)), + ToOwned::to_owned, + ), + ItemKind::Type(ref ty) => ty.sanitized_name(ctx).map_or_else( + || format!("_bindgen_ty_{}", self.exposed_id(ctx)), + Into::into, + ), ItemKind::Function(ref fun) => { let mut name = fun.name().to_owned(); if let Some(idx) = self.overload_index(ctx) { if idx > 0 { - write!(&mut name, "{}", idx).unwrap(); + write!(&mut name, "{idx}").unwrap(); } } @@ -941,13 +938,13 @@ impl Item { // Only use local ids for enums, classes, structs and union types. All // other items use their global ID. let ty_kind = self.kind().as_type().map(|t| t.kind()); - if let Some(ty_kind) = ty_kind { - match *ty_kind { - TypeKind::Comp(..) | - TypeKind::TemplateInstantiation(..) | - TypeKind::Enum(..) => return self.local_id(ctx).to_string(), - _ => {} - } + if let Some( + TypeKind::Comp(..) | + TypeKind::TemplateInstantiation(..) | + TypeKind::Enum(..), + ) = ty_kind + { + return self.local_id(ctx).to_string(); } // Note that this `id_` prefix prevents (really unlikely) collisions @@ -979,9 +976,8 @@ impl Item { // Do not jump through aliases, except for aliases that point to a type // with the same name, since we dont generate coe for them. let item = self.id.into_resolver().through_type_refs().resolve(ctx); - let type_ = match *item.kind() { - ItemKind::Type(ref type_) => type_, - _ => return false, + let ItemKind::Type(ref type_) = *item.kind() else { + return false; }; match *type_.kind() { @@ -1017,15 +1013,15 @@ impl Item { FunctionKind::Method(MethodKind::Constructor) => { cc.constructors() } - FunctionKind::Method(MethodKind::Destructor) | - FunctionKind::Method(MethodKind::VirtualDestructor { - .. - }) => cc.destructors(), - FunctionKind::Method(MethodKind::Static) | - FunctionKind::Method(MethodKind::Normal) | - FunctionKind::Method(MethodKind::Virtual { .. }) => { - cc.methods() - } + FunctionKind::Method( + MethodKind::Destructor | + MethodKind::VirtualDestructor { .. }, + ) => cc.destructors(), + FunctionKind::Method( + MethodKind::Static | + MethodKind::Normal | + MethodKind::Virtual { .. }, + ) => cc.methods(), }, } } @@ -1037,7 +1033,7 @@ impl Item { ctx: &BindgenContext, ) -> &Vec { self.path_for_allowlisting - .borrow_with(|| self.compute_path(ctx, UserMangled::No)) + .get_or_init(|| self.compute_path(ctx, UserMangled::No)) } fn compute_path( @@ -1059,7 +1055,7 @@ impl Item { .map(|id| ctx.resolve_item(id)) .filter(|item| { item.id() == target.id() || - item.as_module().map_or(false, |module| { + item.as_module().is_some_and(|module| { !module.is_inline() || ctx.options().conservative_inline_namespaces }) @@ -1078,9 +1074,8 @@ impl Item { /// Returns a prefix for the canonical name when C naming is enabled. fn c_naming_prefix(&self) -> Option<&str> { - let ty = match self.kind { - ItemKind::Type(ref ty) => ty, - _ => return None, + let ItemKind::Type(ref ty) = self.kind else { + return None; }; Some(match ty.kind() { @@ -1123,7 +1118,7 @@ impl IsOpaque for Item { "You're not supposed to call this yet" ); self.annotations.opaque() || - self.as_type().map_or(false, |ty| ty.is_opaque(ctx, self)) || + self.as_type().is_some_and(|ty| ty.is_opaque(ctx, self)) || ctx.opaque_by_name(self.path_for_allowlisting(ctx)) } } @@ -1134,14 +1129,14 @@ where { fn has_vtable(&self, ctx: &BindgenContext) -> bool { let id: ItemId = (*self).into(); - id.as_type_id(ctx).map_or(false, |id| { + id.as_type_id(ctx).is_some_and(|id| { !matches!(ctx.lookup_has_vtable(id), HasVtableResult::No) }) } fn has_vtable_ptr(&self, ctx: &BindgenContext) -> bool { let id: ItemId = (*self).into(); - id.as_type_id(ctx).map_or(false, |id| { + id.as_type_id(ctx).is_some_and(|id| { matches!(ctx.lookup_has_vtable(id), HasVtableResult::SelfHasVtable) }) } @@ -1421,11 +1416,7 @@ impl Item { CXCursor_UsingDirective | CXCursor_StaticAssert | CXCursor_FunctionTemplate => { - debug!( - "Unhandled cursor kind {:?}: {:?}", - cursor.kind(), - cursor - ); + debug!("Unhandled cursor kind {:?}: {cursor:?}", cursor.kind()); Err(ParseError::Continue) } @@ -1433,7 +1424,7 @@ impl Item { let file = cursor.get_included_file_name(); match file { None => { - warn!("Inclusion of a nameless file in {:?}", cursor); + warn!("Inclusion of a nameless file in {cursor:?}"); } Some(included_file) => { for cb in &ctx.options().parse_callbacks { @@ -1451,9 +1442,8 @@ impl Item { let spelling = cursor.spelling(); if !spelling.starts_with("operator") { warn!( - "Unhandled cursor kind {:?}: {:?}", + "Unhandled cursor kind {:?}: {cursor:?}", cursor.kind(), - cursor ); } Err(ParseError::Continue) @@ -1490,10 +1480,7 @@ impl Item { parent_id: Option, ctx: &mut BindgenContext, ) -> TypeId { - debug!( - "from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}", - potential_id, ty, location, parent_id - ); + debug!("from_ty_or_ref_with_id: {potential_id:?} {ty:?}, {location:?}, {parent_id:?}"); if ctx.collected_typerefs() { debug!("refs already collected, resolving directly"); @@ -1513,11 +1500,11 @@ impl Item { &ty, Some(location), ) { - debug!("{:?} already resolved: {:?}", ty, location); + debug!("{ty:?} already resolved: {location:?}"); return ty; } - debug!("New unresolved type reference: {:?}, {:?}", ty, location); + debug!("New unresolved type reference: {ty:?}, {location:?}"); let is_const = ty.is_const(); let kind = TypeKind::UnresolvedTypeRef(ty, location, parent_id); @@ -1567,14 +1554,13 @@ impl Item { use clang_sys::*; debug!( - "Item::from_ty_with_id: {:?}\n\ - \tty = {:?},\n\ - \tlocation = {:?}", - id, ty, location + "Item::from_ty_with_id: {id:?}\n\ + \tty = {ty:?},\n\ + \tlocation = {location:?}", ); - if ty.kind() == clang_sys::CXType_Unexposed || - location.cur_type().kind() == clang_sys::CXType_Unexposed + if ty.kind() == CXType_Unexposed || + location.cur_type().kind() == CXType_Unexposed { if ty.is_associated_type() || location.cur_type().is_associated_type() @@ -1594,7 +1580,7 @@ impl Item { // ignore function bodies. See issue #2036.) if let Some(ref parent) = ty.declaration().fallible_semantic_parent() { if FunctionKind::from_cursor(parent).is_some() { - debug!("Skipping type declared inside function: {:?}", ty); + debug!("Skipping type declared inside function: {ty:?}"); return Ok(Item::new_opaque_type(id, ty, ctx)); } } @@ -1604,10 +1590,7 @@ impl Item { canonical_def.unwrap_or_else(|| ty.declaration()) }; - let comment = location - .raw_comment() - .or_else(|| decl.raw_comment()) - .or_else(|| location.raw_comment()); + let comment = location.raw_comment().or_else(|| decl.raw_comment()); let annotations = Annotations::new(&decl).or_else(|| Annotations::new(&location)); @@ -1641,7 +1624,7 @@ impl Item { .iter() .find(|ty| *ty.decl() == declaration_to_look_for) { - debug!("Avoiding recursion parsing type: {:?}", ty); + debug!("Avoiding recursion parsing type: {ty:?}"); // Unchecked because we haven't finished this type yet. return Ok(partial.id().as_type_id_unchecked()); } @@ -1712,8 +1695,7 @@ impl Item { ty.spelling() ); Item::type_param(Some(id), location, ctx) - .map(Ok) - .unwrap_or(Err(ParseError::Recurse)) + .ok_or(ParseError::Recurse) } else { result } @@ -1807,10 +1789,10 @@ impl Item { refd: &clang::Cursor, spelling: &str, ) -> bool { - lazy_static! { - static ref ANON_TYPE_PARAM_RE: regex::Regex = - regex::Regex::new(r"^type\-parameter\-\d+\-\d+$").unwrap(); - } + static ANON_TYPE_PARAM_RE: OnceLock = OnceLock::new(); + let anon_type_param_re = ANON_TYPE_PARAM_RE.get_or_init(|| { + regex::Regex::new(r"^type\-parameter\-\d+\-\d+$").unwrap() + }); if refd.kind() != clang_sys::CXCursor_TemplateTypeParameter { return false; @@ -1819,7 +1801,7 @@ impl Item { let refd_spelling = refd.spelling(); refd_spelling == spelling || // Allow for anonymous template parameters. - (refd_spelling.is_empty() && ANON_TYPE_PARAM_RE.is_match(spelling.as_ref())) + (refd_spelling.is_empty() && anon_type_param_re.is_match(spelling.as_ref())) } let definition = if is_template_with_spelling(&location, &ty_spelling) { @@ -1872,16 +1854,11 @@ impl Item { let parent = ctx.root_module().into(); if let Some(id) = ctx.get_type_param(&definition) { - if let Some(with_id) = with_id { - return Some(ctx.build_ty_wrapper( - with_id, - id, - Some(parent), - &ty, - )); + return Some(if let Some(with_id) = with_id { + ctx.build_ty_wrapper(with_id, id, Some(parent), &ty) } else { - return Some(id); - } + id + }); } // See tests/headers/const_tparam.hpp and @@ -1909,7 +1886,7 @@ impl ItemCanonicalName for Item { "You're not supposed to call this yet" ); self.canonical_name - .borrow_with(|| { + .get_or_init(|| { let in_namespace = ctx.options().enable_cxx_namespaces || ctx.options().disable_name_namespacing; diff --git a/bindgen/ir/layout.rs b/bindgen/ir/layout.rs index 85a553da31..905e47c732 100644 --- a/bindgen/ir/layout.rs +++ b/bindgen/ir/layout.rs @@ -19,9 +19,8 @@ pub(crate) struct Layout { #[test] fn test_layout_for_size() { - use std::mem; - - let ptr_size = mem::size_of::<*mut ()>(); + use std::mem::size_of; + let ptr_size = size_of::<*mut ()>(); assert_eq!( Layout::for_size_internal(ptr_size, ptr_size), Layout::new(ptr_size, ptr_size) @@ -34,14 +33,9 @@ fn test_layout_for_size() { impl Layout { /// Gets the integer type name for a given known size. - pub(crate) fn known_type_for_size( - ctx: &BindgenContext, - size: usize, - ) -> Option { + pub(crate) fn known_type_for_size(size: usize) -> Option { Some(match size { - 16 if ctx.options().rust_features.i128_and_u128 => { - syn::parse_quote! { u128 } - } + 16 => syn::parse_quote! { u128 }, 8 => syn::parse_quote! { u64 }, 4 => syn::parse_quote! { u32 }, 2 => syn::parse_quote! { u16 }, @@ -102,17 +96,14 @@ impl Opaque { /// Return the known rust type we should use to create a correctly-aligned /// field with this layout. - pub(crate) fn known_rust_type_for_array( - &self, - ctx: &BindgenContext, - ) -> Option { - Layout::known_type_for_size(ctx, self.0.align) + pub(crate) fn known_rust_type_for_array(&self) -> Option { + Layout::known_type_for_size(self.0.align) } /// Return the array size that an opaque type for this layout should have if /// we know the correct type for it, or `None` otherwise. - pub(crate) fn array_size(&self, ctx: &BindgenContext) -> Option { - if self.known_rust_type_for_array(ctx).is_some() { + pub(crate) fn array_size(&self) -> Option { + if self.known_rust_type_for_array().is_some() { Some(self.0.size / cmp::max(self.0.align, 1)) } else { None @@ -122,13 +113,10 @@ impl Opaque { /// Return `true` if this opaque layout's array size will fit within the /// maximum number of array elements that Rust allows deriving traits /// with. Return `false` otherwise. - pub(crate) fn array_size_within_derive_limit( - &self, - ctx: &BindgenContext, - ) -> CanDerive { + pub(crate) fn array_size_within_derive_limit(&self) -> CanDerive { if self - .array_size(ctx) - .map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + .array_size() + .is_some_and(|size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) { CanDerive::Yes } else { diff --git a/bindgen/ir/module.rs b/bindgen/ir/module.rs index 5ec55e9048..4788cf4285 100644 --- a/bindgen/ir/module.rs +++ b/bindgen/ir/module.rs @@ -84,8 +84,8 @@ impl ClangSubItemParser for Module { let module_id = ctx.module(cursor); ctx.with_module(module_id, |ctx| { cursor.visit_sorted(ctx, |ctx, child| { - parse_one(ctx, child, Some(module_id.into())) - }) + parse_one(ctx, child, Some(module_id.into())); + }); }); Ok(ParseResult::AlreadyResolved(module_id.into())) diff --git a/bindgen/ir/objc.rs b/bindgen/ir/objc.rs index d7f7cc65a6..6cdadb131d 100644 --- a/bindgen/ir/objc.rs +++ b/bindgen/ir/objc.rs @@ -17,20 +17,20 @@ use clang_sys::CXCursor_ObjCSuperClassRef; use clang_sys::CXCursor_TemplateTypeParameter; use proc_macro2::{Ident, Span, TokenStream}; -/// Objective C interface as used in TypeKind +/// Objective-C interface as used in `TypeKind` /// -/// Also protocols and categories are parsed as this type +/// Also, protocols and categories are parsed as this type #[derive(Debug)] pub(crate) struct ObjCInterface { /// The name - /// like, NSObject + /// like, `NSObject` name: String, category: Option, is_protocol: bool, - /// The list of template names almost always, ObjectType or KeyType + /// The list of template names almost always, `ObjectType` or `KeyType` pub(crate) template_names: Vec, /// The list of protocols that this interface conforms to. @@ -53,7 +53,7 @@ pub(crate) struct ObjCMethod { name: String, /// Method name as converted to rust - /// like, dataWithBytes_length_ + /// like, `dataWithBytes_length`_ rust_name: String, signature: FunctionSig, @@ -77,17 +77,17 @@ impl ObjCInterface { } /// The name - /// like, NSObject + /// like, `NSObject` pub(crate) fn name(&self) -> &str { self.name.as_ref() } /// Formats the name for rust - /// Can be like NSObject, but with categories might be like NSObject_NSCoderMethods - /// and protocols are like PNSObject + /// Can be like `NSObject`, but with categories might be like `NSObject_NSCoderMethods` + /// and protocols are like `PNSObject` pub(crate) fn rust_name(&self) -> String { if let Some(ref cat) = self.category { - format!("{}_{}", self.name(), cat) + format!("{}_{cat}", self.name()) } else if self.is_protocol { format!("P{}", self.name()) } else { @@ -147,8 +147,8 @@ impl ObjCInterface { let needle = format!("P{}", c.spelling()); let items_map = ctx.items(); debug!( - "Interface {} conforms to {}, find the item", - interface.name, needle + "Interface {} conforms to {needle}, find the item", + interface.name, ); for (id, item) in items_map { @@ -163,10 +163,7 @@ impl ObjCInterface { ty.name() ); if Some(needle.as_ref()) == ty.name() { - debug!( - "Found conforming protocol {:?}", - item - ); + debug!("Found conforming protocol {item:?}"); interface.conforms_to.push(id); break; } @@ -230,12 +227,12 @@ impl ObjCMethod { } /// Method name as converted to rust - /// like, dataWithBytes_length_ + /// like, `dataWithBytes_length`_ pub(crate) fn rust_name(&self) -> &str { self.rust_name.as_ref() } - /// Returns the methods signature as FunctionSig + /// Returns the methods signature as `FunctionSig` pub(crate) fn signature(&self) -> &FunctionSig { &self.signature } @@ -262,10 +259,7 @@ impl ObjCMethod { // unless it is `crate`, `self`, `super` or `Self`, so we try to add the `_` // suffix to it and parse it. if ["crate", "self", "super", "Self"].contains(&name) { - Some(Ident::new( - &format!("{}_", name), - Span::call_site(), - )) + Some(Ident::new(&format!("{name}_"), Span::call_site())) } else { Some(Ident::new(name, Span::call_site())) } @@ -278,11 +272,11 @@ impl ObjCMethod { Some( syn::parse_str::(name) .or_else(|err| { - syn::parse_str::(&format!("r#{}", name)) + syn::parse_str::(&format!("r#{name}")) .map_err(|_| err) }) .or_else(|err| { - syn::parse_str::(&format!("{}_", name)) + syn::parse_str::(&format!("{name}_")) .map_err(|_| err) }) .expect("Invalid identifier"), @@ -300,20 +294,15 @@ impl ObjCMethod { } // Check right amount of arguments - assert!( - args.len() == split_name.len() - 1, - "Incorrect method name or arguments for objc method, {:?} vs {:?}", - args, - split_name - ); + assert_eq!(args.len(), split_name.len() - 1, "Incorrect method name or arguments for objc method, {args:?} vs {split_name:?}"); // Get arguments without type signatures to pass to `msg_send!` let mut args_without_types = vec![]; - for arg in args.iter() { + for arg in args { let arg = arg.to_string(); let name_and_sig: Vec<&str> = arg.split(' ').collect(); let name = name_and_sig[0]; - args_without_types.push(Ident::new(name, Span::call_site())) + args_without_types.push(Ident::new(name, Span::call_site())); } let args = split_name.into_iter().zip(args_without_types).map( diff --git a/bindgen/ir/template.rs b/bindgen/ir/template.rs index 4dd8442c58..7f3667879d 100644 --- a/bindgen/ir/template.rs +++ b/bindgen/ir/template.rs @@ -4,7 +4,7 @@ //! brief definitions: //! //! * "Template definition": a class/struct/alias/function definition that takes -//! generic template parameters. For example: +//! generic template parameters. For example: //! //! ```c++ //! template @@ -14,11 +14,11 @@ //! ``` //! //! * "Template instantiation": an instantiation is a use of a template with -//! concrete template arguments. For example, `List`. +//! concrete template arguments. For example, `List`. //! //! * "Template specialization": an alternative template definition providing a -//! custom definition for instantiations with the matching template -//! arguments. This C++ feature is unsupported by bindgen. For example: +//! custom definition for instantiations with the matching template +//! arguments. This C++ feature is unsupported by bindgen. For example: //! //! ```c++ //! template<> @@ -77,27 +77,23 @@ use crate::clang; /// The following table depicts the results of each trait method when invoked on /// each of the declarations above: /// -/// +------+----------------------+--------------------------+-------------------------+---- -/// |Decl. | self_template_params | num_self_template_params | all_template_parameters | ... -/// +------+----------------------+--------------------------+-------------------------+---- -/// |Foo | T, U | 2 | T, U | ... -/// |Bar | V | 1 | T, U, V | ... -/// |Inner | | 0 | T, U | ... -/// |Lol | W | 1 | T, U, W | ... -/// |Wtf | X | 1 | T, U, X | ... -/// |Qux | | 0 | | ... -/// +------+----------------------+--------------------------+------------------------+---- +/// |Decl. | self_template_params | num_self_template_params | all_template_parameters | +/// |------|----------------------|--------------------------|-------------------------| +/// |Foo | T, U | 2 | T, U | +/// |Bar | V | 1 | T, U, V | +/// |Inner | | 0 | T, U | +/// |Lol | W | 1 | T, U, W | +/// |Wtf | X | 1 | T, U, X | +/// |Qux | | 0 | | /// -/// ----+------+-----+----------------------+ -/// ... |Decl. | ... | used_template_params | -/// ----+------+-----+----------------------+ -/// ... |Foo | ... | T, U | -/// ... |Bar | ... | V | -/// ... |Inner | ... | | -/// ... |Lol | ... | T | -/// ... |Wtf | ... | T | -/// ... |Qux | ... | | -/// ----+------+-----+----------------------+ +/// | Decl. | used_template_params | +/// |-------|----------------------| +/// | Foo | T, U | +/// | Bar | V | +/// | Inner | | +/// | Lol | T | +/// | Wtf | T | +/// | Qux | | pub(crate) trait TemplateParameters: Sized { /// Get the set of `ItemId`s that make up this template declaration's free /// template parameters. @@ -266,17 +262,14 @@ impl TemplateInstantiation { }) }; - let definition = match definition { - Some(def) => def, - None => { - if !ty.declaration().is_builtin() { - warn!( - "Could not find template definition for template \ + let Some(definition) = definition else { + if !ty.declaration().is_builtin() { + warn!( + "Could not find template definition for template \ instantiation" - ); - } - return None; + ); } + return None; }; let template_definition = diff --git a/bindgen/ir/traversal.rs b/bindgen/ir/traversal.rs index 17e24f701e..01f3a8bd50 100644 --- a/bindgen/ir/traversal.rs +++ b/bindgen/ir/traversal.rs @@ -235,7 +235,7 @@ pub(crate) fn codegen_edges(ctx: &BindgenContext, edge: Edge) -> bool { /// outgoing edges might not have been fully traversed yet) in an active /// traversal. pub(crate) trait TraversalStorage<'ctx> { - /// Construct a new instance of this TraversalStorage, for a new traversal. + /// Construct a new instance of this `TraversalStorage`, for a new traversal. fn new(ctx: &'ctx BindgenContext) -> Self; /// Add the given item to the storage. If the item has never been seen @@ -287,8 +287,7 @@ impl<'ctx> TraversalStorage<'ctx> for Paths<'ctx> { } path.reverse(); panic!( - "Found reference to dangling id = {:?}\nvia path = {:?}", - item, path + "Found reference to dangling id = {item:?}\nvia path = {path:?}" ); } @@ -345,7 +344,7 @@ where F: FnMut(ItemId, EdgeKind), { fn visit_kind(&mut self, item: ItemId, kind: EdgeKind) { - (*self)(item, kind) + (*self)(item, kind); } } @@ -438,7 +437,7 @@ where let is_newly_discovered = self.seen.add(self.currently_traversing, item); if is_newly_discovered { - self.queue.push(item) + self.queue.push(item); } } } diff --git a/bindgen/ir/ty.rs b/bindgen/ir/ty.rs index 2a24dd0291..baaa4a4907 100644 --- a/bindgen/ir/ty.rs +++ b/bindgen/ir/ty.rs @@ -248,7 +248,7 @@ impl Type { return Cow::Borrowed(name); } - let name = name.replace(|c| c == ' ' || c == ':' || c == '.', "_"); + let name = name.replace([' ', ':', '.'], "_"); Cow::Owned(name) } @@ -261,7 +261,7 @@ impl Type { TypeKind::Pointer(inner) => Some((inner, Cow::Borrowed("ptr"))), TypeKind::Reference(inner) => Some((inner, Cow::Borrowed("ref"))), TypeKind::Array(inner, length) => { - Some((inner, format!("array{}", length).into())) + Some((inner, format!("array{length}").into())) } _ => None, }; @@ -269,13 +269,13 @@ impl Type { ctx.resolve_item(inner) .expect_type() .sanitized_name(ctx) - .map(|name| format!("{}_{}", prefix, name).into()) + .map(|name| format!("{prefix}_{name}").into()) } else { self.name().map(Self::sanitize_name) } } - /// See safe_canonical_type. + /// See [`Self::safe_canonical_type`]. pub(crate) fn canonical_type<'tr>( &'tr self, ctx: &'tr BindgenContext, @@ -471,7 +471,7 @@ impl TypeKind { #[test] fn is_invalid_type_param_valid() { let ty = Type::new(Some("foo".into()), None, TypeKind::TypeParam, false); - assert!(!ty.is_invalid_type_param()) + assert!(!ty.is_invalid_type_param()); } #[test] @@ -482,38 +482,38 @@ fn is_invalid_type_param_valid_underscore_and_numbers() { TypeKind::TypeParam, false, ); - assert!(!ty.is_invalid_type_param()) + assert!(!ty.is_invalid_type_param()); } #[test] fn is_invalid_type_param_valid_unnamed_kind() { let ty = Type::new(Some("foo".into()), None, TypeKind::Void, false); - assert!(!ty.is_invalid_type_param()) + assert!(!ty.is_invalid_type_param()); } #[test] fn is_invalid_type_param_invalid_start() { let ty = Type::new(Some("1foo".into()), None, TypeKind::TypeParam, false); - assert!(ty.is_invalid_type_param()) + assert!(ty.is_invalid_type_param()); } #[test] fn is_invalid_type_param_invalid_remaining() { let ty = Type::new(Some("foo-".into()), None, TypeKind::TypeParam, false); - assert!(ty.is_invalid_type_param()) + assert!(ty.is_invalid_type_param()); } #[test] -#[should_panic] +#[should_panic(expected = "Unnamed named type")] fn is_invalid_type_param_unnamed() { let ty = Type::new(None, None, TypeKind::TypeParam, false); - assert!(ty.is_invalid_type_param()) + assert!(ty.is_invalid_type_param()); } #[test] fn is_invalid_type_param_empty_name() { - let ty = Type::new(Some("".into()), None, TypeKind::TypeParam, false); - assert!(ty.is_invalid_type_param()) + let ty = Type::new(Some(String::new()), None, TypeKind::TypeParam, false); + assert!(ty.is_invalid_type_param()); } impl TemplateParameters for Type { @@ -582,7 +582,7 @@ pub(crate) enum TypeKind { /// A compound type, that is, a class, struct, or union. Comp(CompInfo), - /// An opaque type that we just don't understand. All usage of this shoulf + /// An opaque type that we just don't understand. All usage of this should /// result in an opaque blob of bytes generated from the containing type's /// layout. Opaque, @@ -623,7 +623,7 @@ pub(crate) enum TypeKind { /// A pointer to an Apple block. BlockPointer(TypeId), - /// A reference to a type, as in: int& foo(). + /// A reference to a type, as in: int& `foo()`. Reference(TypeId), /// An instantiation of an abstract template definition with a set of @@ -634,15 +634,10 @@ pub(crate) enum TypeKind { /// itself, and postpones its resolution. /// /// These are gone in a phase after parsing where these are mapped to - /// already known types, and are converted to ResolvedTypeRef. + /// already known types, and are converted to `ResolvedTypeRef`. /// /// see tests/headers/typeref.hpp to see somewhere where this is a problem. - UnresolvedTypeRef( - clang::Type, - clang::Cursor, - /* parent_id */ - Option, - ), + UnresolvedTypeRef(clang::Type, Cursor, /* parent_id */ Option), /// An indirection to another type. /// @@ -685,7 +680,7 @@ impl Type { Some(location), ); if let Some(ty) = already_resolved { - debug!("{:?} already resolved: {:?}", ty, location); + debug!("{ty:?} already resolved: {location:?}"); return Ok(ParseResult::AlreadyResolved(ty.into())); } } @@ -700,8 +695,7 @@ impl Type { }; debug!( - "from_clang_ty: {:?}, ty: {:?}, loc: {:?}", - potential_id, ty, location + "from_clang_ty: {potential_id:?}, ty: {ty:?}, loc: {location:?}" ); debug!("currently_parsed_types: {:?}", ctx.currently_parsed_types()); @@ -711,7 +705,7 @@ impl Type { let mut ty_kind = ty.kind(); match location.kind() { CXCursor_ObjCProtocolDecl | CXCursor_ObjCCategoryDecl => { - ty_kind = CXType_ObjCInterface + ty_kind = CXType_ObjCInterface; } _ => {} } @@ -776,7 +770,7 @@ impl Type { // etc. !canonical_ty.spelling().contains("type-parameter") => { - debug!("Looking for canonical type: {:?}", canonical_ty); + debug!("Looking for canonical type: {canonical_ty:?}"); return Self::from_clang_ty( potential_id, &canonical_ty, @@ -797,10 +791,7 @@ impl Type { // Same here, with template specialisations we can safely // assume this is a Comp(..) } else if ty.is_fully_instantiated_template() { - debug!( - "Template specialization: {:?}, {:?} {:?}", - ty, location, canonical_ty - ); + debug!("Template specialization: {ty:?}, {location:?} {canonical_ty:?}"); let complex = CompInfo::from_ty( potential_id, ty, @@ -869,20 +860,16 @@ impl Type { Some(location), ctx, ); - match complex { - Ok(complex) => TypeKind::Comp(complex), - Err(_) => { - warn!( - "Could not create complex type \ - from class template or base \ - specifier, using opaque blob" - ); - let opaque = - Opaque::from_clang_ty(ty, ctx); - return Ok(ParseResult::New( - opaque, None, - )); - } + if let Ok(complex) = complex { + TypeKind::Comp(complex) + } else { + warn!( + "Could not create complex type \ + from class template or base \ + specifier, using opaque blob" + ); + let opaque = Opaque::from_clang_ty(ty, ctx); + return Ok(ParseResult::New(opaque, None)); } } CXCursor_TypeAliasTemplateDecl => { @@ -930,16 +917,13 @@ impl Type { CXChildVisit_Continue }); - let inner_type = match inner { - Ok(inner) => inner, - Err(..) => { - warn!( - "Failed to parse template alias \ + let Ok(inner_type) = inner else { + warn!( + "Failed to parse template alias \ {:?}", - location - ); - return Err(ParseError::Continue); - } + location + ); + return Err(ParseError::Continue); }; TypeKind::TemplateAlias(inner_type, args) @@ -948,13 +932,7 @@ impl Type { let referenced = location.referenced().unwrap(); let referenced_ty = referenced.cur_type(); - debug!( - "TemplateRef: location = {:?}; referenced = \ - {:?}; referenced_ty = {:?}", - location, - referenced, - referenced_ty - ); + debug!("TemplateRef: location = {location:?}; referenced = {referenced:?}; referenced_ty = {referenced_ty:?}"); return Self::from_clang_ty( potential_id, @@ -969,11 +947,7 @@ impl Type { let referenced_ty = referenced.cur_type(); let declaration = referenced_ty.declaration(); - debug!( - "TypeRef: location = {:?}; referenced = \ - {:?}; referenced_ty = {:?}", - location, referenced, referenced_ty - ); + debug!("TypeRef: location = {location:?}; referenced = {referenced:?}; referenced_ty = {referenced_ty:?}"); let id = Item::from_ty_or_ref_with_id( potential_id, @@ -991,16 +965,11 @@ impl Type { } _ => { if ty.kind() == CXType_Unexposed { - warn!( - "Unexposed type {:?}, recursing inside, \ - loc: {:?}", - ty, - location - ); + warn!("Unexposed type {ty:?}, recursing inside, loc: {location:?}"); return Err(ParseError::Recurse); } - warn!("invalid type {:?}", ty); + warn!("invalid type {ty:?}"); return Err(ParseError::Continue); } } @@ -1008,7 +977,7 @@ impl Type { } CXType_Auto => { if canonical_ty == *ty { - debug!("Couldn't find deduced type: {:?}", ty); + debug!("Couldn't find deduced type: {ty:?}"); return Err(ParseError::Continue); } @@ -1148,7 +1117,7 @@ impl Type { TypeKind::Comp(complex) } - CXType_Vector => { + CXType_Vector | CXType_ExtVector => { let inner = Item::from_ty( ty.elem_type().as_ref().unwrap(), location, @@ -1167,6 +1136,18 @@ impl Type { .expect("Not able to resolve array element?"); TypeKind::Array(inner, ty.num_elements().unwrap()) } + CXType_Atomic => { + // TODO(emilio): Maybe we can preserve the "is atomic" bit somehow and generate + // something more useful... But for now this is better than panicking or + // generating nothing. + return Self::from_clang_ty( + potential_id, + &ty.atomic_value_type(), + location, + parent_id, + ctx, + ); + } CXType_Elaborated => { return Self::from_clang_ty( potential_id, @@ -1191,10 +1172,8 @@ impl Type { } _ => { warn!( - "unsupported type: kind = {:?}; ty = {:?}; at {:?}", + "unsupported type: kind = {:?}; ty = {ty:?}; at {location:?}", ty.kind(), - ty, - location ); return Err(ParseError::Continue); } @@ -1205,8 +1184,7 @@ impl Type { let is_const = ty.is_const() || (ty.kind() == CXType_ConstantArray && - ty.elem_type() - .map_or(false, |element| element.is_const())); + ty.elem_type().is_some_and(|element| element.is_const())); let ty = Type::new(name, layout, kind, is_const); // TODO: maybe declaration.canonical()? @@ -1221,10 +1199,7 @@ impl Trace for Type { where T: Tracer, { - if self - .name() - .map_or(false, |name| context.is_stdint_type(name)) - { + if self.name().is_some_and(|name| context.is_stdint_type(name)) { // These types are special-cased in codegen and don't need to be traversed. return; } diff --git a/bindgen/ir/var.rs b/bindgen/ir/var.rs index a548ec881b..85e127fdbc 100644 --- a/bindgen/ir/var.rs +++ b/bindgen/ir/var.rs @@ -113,11 +113,7 @@ impl DotAttributes for Var { } if let Some(ref mangled) = self.mangled_name { - writeln!( - out, - "mangled name{}", - mangled - )?; + writeln!(out, "mangled name{mangled}")?; } Ok(()) @@ -129,35 +125,32 @@ fn default_macro_constant_type(ctx: &BindgenContext, value: i64) -> IntKind { ctx.options().default_macro_constant_type == MacroTypeVariation::Signed { - if value < i32::min_value() as i64 || value > i32::max_value() as i64 { + if value < i64::from(i32::MIN) || value > i64::from(i32::MAX) { IntKind::I64 } else if !ctx.options().fit_macro_constants || - value < i16::min_value() as i64 || - value > i16::max_value() as i64 + value < i64::from(i16::MIN) || + value > i64::from(i16::MAX) { IntKind::I32 - } else if value < i8::min_value() as i64 || - value > i8::max_value() as i64 - { + } else if value < i64::from(i8::MIN) || value > i64::from(i8::MAX) { IntKind::I16 } else { IntKind::I8 } - } else if value > u32::max_value() as i64 { + } else if value > i64::from(u32::MAX) { IntKind::U64 - } else if !ctx.options().fit_macro_constants || - value > u16::max_value() as i64 + } else if !ctx.options().fit_macro_constants || value > i64::from(u16::MAX) { IntKind::U32 - } else if value > u8::max_value() as i64 { + } else if value > i64::from(u8::MAX) { IntKind::U16 } else { IntKind::U8 } } -/// Parses tokens from a CXCursor_MacroDefinition pointing into a function-like -/// macro, and calls the func_macro callback. +/// Parses tokens from a `CXCursor_MacroDefinition` pointing into a function-like +/// macro, and calls the `func_macro` callback. fn handle_function_macro( cursor: &clang::Cursor, callbacks: &dyn crate::callbacks::ParseCallbacks, @@ -206,9 +199,8 @@ impl ClangSubItemParser for Var { let value = parse_macro(ctx, &cursor); - let (id, value) = match value { - Some(v) => v, - None => return Err(ParseError::Continue), + let Some((id, value)) = value else { + return Err(ParseError::Continue); }; assert!(!id.is_empty(), "Empty macro name?"); @@ -242,10 +234,7 @@ impl ClangSubItemParser for Var { assert_eq!(c.len_utf8(), 1); c as u8 } - CChar::Raw(c) => { - assert!(c <= ::std::u8::MAX as u64); - c as u8 - } + CChar::Raw(c) => u8::try_from(c).unwrap(), }; (TypeKind::Int(IntKind::U8), VarType::Char(c)) @@ -315,7 +304,7 @@ impl ClangSubItemParser for Var { ([CXType_ConstantArray, CXType_IncompleteArray] .contains(&ty.kind()) && ty.elem_type() - .map_or(false, |element| element.is_const())); + .is_some_and(|element| element.is_const())); let ty = match Item::from_ty(&ty, cursor, None, ctx) { Ok(ty) => ty, @@ -324,7 +313,7 @@ impl ClangSubItemParser for Var { matches!(ty.kind(), CXType_Auto | CXType_Unexposed), "Couldn't resolve constant type, and it \ wasn't an nondeductible auto type or unexposed \ - type!" + type: {ty:?}" ); return Err(e); } @@ -338,17 +327,17 @@ impl ClangSubItemParser for Var { .safe_resolve_type(ty) .and_then(|t| t.safe_canonical_type(ctx)); - let is_integer = canonical_ty.map_or(false, |t| t.is_integer()); - let is_float = canonical_ty.map_or(false, |t| t.is_float()); + let is_integer = canonical_ty.is_some_and(|t| t.is_integer()); + let is_float = canonical_ty.is_some_and(|t| t.is_float()); // TODO: We could handle `char` more gracefully. // TODO: Strings, though the lookup is a bit more hard (we need // to look at the canonical type of the pointee too, and check // is char, u8, or i8 I guess). let value = if is_integer { - let kind = match *canonical_ty.unwrap().kind() { - TypeKind::Int(kind) => kind, - _ => unreachable!(), + let TypeKind::Int(kind) = *canonical_ty.unwrap().kind() + else { + unreachable!() }; let mut val = cursor.evaluate().and_then(|v| v.as_int()); @@ -389,9 +378,51 @@ impl ClangSubItemParser for Var { } } +/// This function uses a [`FallbackTranslationUnit`][clang::FallbackTranslationUnit] to parse each +/// macro that cannot be parsed by the normal bindgen process for `#define`s. +/// +/// To construct the [`FallbackTranslationUnit`][clang::FallbackTranslationUnit], first precompiled +/// headers are generated for all input headers. An empty temporary `.c` file is generated to pass +/// to the translation unit. On the evaluation of each macro, a [`String`] is generated with the +/// new contents of the empty file and passed in for reparsing. The precompiled headers and +/// preservation of the [`FallbackTranslationUnit`][clang::FallbackTranslationUnit] across macro +/// evaluations are both optimizations that have significantly improved the performance. +fn parse_macro_clang_fallback( + ctx: &mut BindgenContext, + cursor: &clang::Cursor, +) -> Option<(Vec, cexpr::expr::EvalResult)> { + if !ctx.options().clang_macro_fallback { + return None; + } + + let ftu = ctx.try_ensure_fallback_translation_unit()?; + let contents = format!("int main() {{ {}; }}", cursor.spelling()); + ftu.reparse(&contents).ok()?; + // Children of root node of AST + let root_children = ftu.translation_unit().cursor().collect_children(); + // Last child in root is function declaration + // Should be FunctionDecl + let main_func = root_children.last()?; + // Children should all be statements in function declaration + let all_stmts = main_func.collect_children(); + // First child in all_stmts should be the statement containing the macro to evaluate + // Should be CompoundStmt + let macro_stmt = all_stmts.first()?; + // Children should all be expressions from the compound statement + let paren_exprs = macro_stmt.collect_children(); + // First child in all_exprs is the expression utilizing the given macro to be evaluated + // Should be ParenExpr + let paren = paren_exprs.first()?; + + Some(( + cursor.spelling().into_bytes(), + cexpr::expr::EvalResult::Int(Wrapping(paren.evaluate()?.as_int()?)), + )) +} + /// Try and parse a macro using all the macros parsed until now. fn parse_macro( - ctx: &BindgenContext, + ctx: &mut BindgenContext, cursor: &clang::Cursor, ) -> Option<(Vec, cexpr::expr::EvalResult)> { use cexpr::expr; @@ -402,7 +433,7 @@ fn parse_macro( match parser.macro_definition(&cexpr_tokens) { Ok((_, (id, val))) => Some((id.into(), val)), - _ => None, + _ => parse_macro_clang_fallback(ctx, cursor), } } @@ -443,15 +474,15 @@ fn get_integer_literal_from_cursor(cursor: &clang::Cursor) -> Option { fn duplicated_macro_diagnostic( macro_name: &str, - _location: crate::clang::SourceLocation, + _location: clang::SourceLocation, _ctx: &BindgenContext, ) { - warn!("Duplicated macro definition: {}", macro_name); + warn!("Duplicated macro definition: {macro_name}"); #[cfg(feature = "experimental")] // FIXME (pvdrz & amanjeev): This diagnostic message shows way too often to be actually // useful. We have to change the logic where this function is called to be able to emit this - // message only when the duplication is an actuall issue. + // message only when the duplication is an actual issue. // // If I understood correctly, `bindgen` ignores all `#undef` directives. Meaning that this: // ```c @@ -480,7 +511,7 @@ fn duplicated_macro_diagnostic( slice.with_source(source); Diagnostic::default() - .with_title("Duplicated macro definition.", Level::Warn) + .with_title("Duplicated macro definition.", Level::Warning) .add_slice(slice) .add_annotation("This macro had a duplicate.", Level::Note) .display(); diff --git a/bindgen/lib.rs b/bindgen/lib.rs index c2df8a8a1f..12ac8a2998 100644 --- a/bindgen/lib.rs +++ b/bindgen/lib.rs @@ -19,8 +19,6 @@ #[macro_use] extern crate bitflags; #[macro_use] -extern crate lazy_static; -#[macro_use] extern crate quote; #[cfg(feature = "logging")] @@ -52,12 +50,11 @@ mod regex_set; pub use codegen::{ AliasVariation, EnumVariation, MacroTypeVariation, NonCopyUnionStyle, }; -#[cfg(feature = "__cli")] -pub use features::RUST_TARGET_STRINGS; -pub use features::{RustTarget, LATEST_STABLE_RUST}; +pub use features::{RustEdition, RustTarget, LATEST_STABLE_RUST}; pub use ir::annotations::FieldVisibilityKind; pub use ir::function::Abi; -pub use regex_set::RegexSet; +#[cfg(feature = "__cli")] +pub use options::cli::builder_from_flags; use codegen::CodegenError; use features::RustFeatures; @@ -73,6 +70,7 @@ use std::env; use std::ffi::OsStr; use std::fs::{File, OpenOptions}; use std::io::{self, Write}; +use std::mem::size_of; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::rc::Rc; @@ -88,10 +86,12 @@ pub const DEFAULT_ANON_FIELDS_PREFIX: &str = "__bindgen_anon_"; const DEFAULT_NON_EXTERN_FNS_SUFFIX: &str = "__extern"; fn file_is_cpp(name_file: &str) -> bool { - name_file.ends_with(".hpp") || - name_file.ends_with(".hxx") || - name_file.ends_with(".hh") || - name_file.ends_with(".h++") + Path::new(name_file).extension().is_some_and(|ext| { + ext.eq_ignore_ascii_case("hpp") || + ext.eq_ignore_ascii_case("hxx") || + ext.eq_ignore_ascii_case("hh") || + ext.eq_ignore_ascii_case("h++") + }) } fn args_are_cpp(clang_args: &[Box]) -> bool { @@ -194,7 +194,7 @@ impl FromStr for Formatter { "rustfmt" => Ok(Self::Rustfmt), #[cfg(feature = "prettyplease")] "prettyplease" => Ok(Self::Prettyplease), - _ => Err(format!("`{}` is not a valid formatter", s)), + _ => Err(format!("`{s}` is not a valid formatter")), } } } @@ -208,7 +208,7 @@ impl std::fmt::Display for Formatter { Self::Prettyplease => "prettyplease", }; - s.fmt(f) + std::fmt::Display::fmt(&s, f) } } @@ -238,6 +238,7 @@ impl std::fmt::Display for Formatter { /// 2. [`bitfield_enum()`](#method.bitfield_enum) /// 3. [`newtype_enum()`](#method.newtype_enum) /// 4. [`rustified_enum()`](#method.rustified_enum) +/// 5. [`rustified_non_exhaustive_enum()`](#method.rustified_non_exhaustive_enum) /// /// For each C enum, bindgen tries to match the pattern in the following order: /// @@ -318,6 +319,22 @@ fn get_extra_clang_args( impl Builder { /// Generate the Rust bindings using the options built up thus far. pub fn generate(mut self) -> Result { + // Keep rust_features synced with rust_target + self.options.rust_features = match self.options.rust_edition { + Some(edition) => { + if !edition.is_available(self.options.rust_target) { + return Err(BindgenError::UnsupportedEdition( + edition, + self.options.rust_target, + )); + } + RustFeatures::new(self.options.rust_target, edition) + } + None => { + RustFeatures::new_with_latest_edition(self.options.rust_target) + } + }; + // Add any extra arguments from the environment to the clang command line. self.options.clang_args.extend( get_extra_clang_args(&self.options.parse_callbacks) @@ -331,6 +348,18 @@ impl Builder { } // Transform input headers to arguments on the clang command line. + self.options.fallback_clang_args = self + .options + .clang_args + .iter() + .filter(|arg| { + !arg.starts_with("-MMD") && + !arg.starts_with("-MD") && + !arg.starts_with("--write-user-dependencies") && + !arg.starts_with("--user-dependencies") + }) + .cloned() + .collect::>(); self.options.clang_args.extend( self.options.input_headers [..self.options.input_headers.len().saturating_sub(1)] @@ -346,7 +375,7 @@ impl Builder { }) .collect::>(); - Bindings::generate(self.options, input_unsaved_files) + Bindings::generate(self.options, &input_unsaved_files) } /// Preprocess and dump the input header files to disk. @@ -527,25 +556,11 @@ impl BindgenOptions { for regex_set in self.abi_overrides.values_mut().chain(regex_sets) { regex_set.build(record_matches); } - - let rust_target = self.rust_target; - #[allow(deprecated)] - if rust_target <= RustTarget::Stable_1_30 { - deprecated_target_diagnostic(rust_target, self); - } - - // Disable `untagged_union` if the target does not support it. - if !self.rust_features.untagged_union { - self.untagged_union = false; - } } /// Update rust target version pub fn set_rust_target(&mut self, rust_target: RustTarget) { self.rust_target = rust_target; - - // Keep rust_features synced with rust_target - self.rust_features = rust_target.into(); } /// Get features supported by target Rust version @@ -560,7 +575,7 @@ impl BindgenOptions { self.parse_callbacks .iter() .filter_map(|cb| f(cb.as_ref())) - .last() + .next_back() } fn all_callbacks( @@ -579,36 +594,15 @@ impl BindgenOptions { fn process_comment(&self, comment: &str) -> String { let comment = comment::preprocess(comment); - self.parse_callbacks - .last() - .and_then(|cb| cb.process_comment(&comment)) + self.last_callback(|cb| cb.process_comment(&comment)) .unwrap_or(comment) } } -fn deprecated_target_diagnostic(target: RustTarget, _options: &BindgenOptions) { - warn!("The {} Rust target is deprecated. If you have a need to use this target please report it at https://github.com/rust-lang/rust-bindgen/issues", target); - - #[cfg(feature = "experimental")] - if _options.emit_diagnostics { - use crate::diagnostics::{Diagnostic, Level}; - - let mut diagnostic = Diagnostic::default(); - diagnostic.with_title( - format!("The {} Rust target is deprecated.", target), - Level::Warn, - ); - diagnostic.add_annotation( - "This Rust target was passed to `--rust-target`", - Level::Info, - ); - diagnostic.add_annotation("If you have a good reason to use this target please report it at https://github.com/rust-lang/rust-bindgen/issues", Level::Help); - diagnostic.display(); - } -} - #[cfg(feature = "runtime")] fn ensure_libclang_is_loaded() { + use std::sync::{Arc, OnceLock}; + if clang_sys::is_loaded() { return; } @@ -617,17 +611,14 @@ fn ensure_libclang_is_loaded() { // doesn't get dropped prematurely, nor is loaded multiple times // across different threads. - lazy_static! { - static ref LIBCLANG: std::sync::Arc = { - clang_sys::load().expect("Unable to find libclang"); - clang_sys::get_library().expect( - "We just loaded libclang and it had better still be \ - here!", - ) - }; - } + static LIBCLANG: OnceLock> = OnceLock::new(); + let libclang = LIBCLANG.get_or_init(|| { + clang_sys::load().expect("Unable to find libclang"); + clang_sys::get_library() + .expect("We just loaded libclang and it had better still be here!") + }); - clang_sys::set_library(Some(LIBCLANG.clone())); + clang_sys::set_library(Some(libclang.clone())); } #[cfg(not(feature = "runtime"))] @@ -647,6 +638,8 @@ pub enum BindgenError { ClangDiagnostic(String), /// Code generation reported an error. Codegen(CodegenError), + /// The passed edition is not available on that Rust target. + UnsupportedEdition(RustEdition, RustTarget), } impl std::fmt::Display for BindgenError { @@ -662,10 +655,13 @@ impl std::fmt::Display for BindgenError { write!(f, "header '{}' does not exist.", h.display()) } BindgenError::ClangDiagnostic(message) => { - write!(f, "clang diagnosed error: {}", message) + write!(f, "clang diagnosed error: {message}") } BindgenError::Codegen(err) => { - write!(f, "codegen error: {}", err) + write!(f, "codegen error: {err}") + } + BindgenError::UnsupportedEdition(edition, target) => { + write!(f, "edition {edition} is not available on Rust {target}") } } } @@ -686,45 +682,46 @@ pub(crate) const HOST_TARGET: &str = // Some architecture triplets are different between rust and libclang, see #1211 // and duplicates. fn rust_to_clang_target(rust_target: &str) -> Box { - if rust_target.starts_with("aarch64-apple-") { - let mut clang_target = "arm64-apple-".to_owned(); - clang_target - .push_str(rust_target.strip_prefix("aarch64-apple-").unwrap()); - return clang_target.into(); - } else if rust_target.starts_with("riscv64gc-") { - let mut clang_target = "riscv64-".to_owned(); - clang_target.push_str(rust_target.strip_prefix("riscv64gc-").unwrap()); - return clang_target.into(); - } else if rust_target.starts_with("riscv64imac-") { - let mut clang_target = "riscv64-".to_owned(); - clang_target - .push_str(rust_target.strip_prefix("riscv64imac-").unwrap()); - return clang_target.into(); - } else if rust_target.ends_with("-espidf") { - let mut clang_target = - rust_target.strip_suffix("-espidf").unwrap().to_owned(); - clang_target.push_str("-elf"); - if clang_target.starts_with("riscv32imc-") { - clang_target = "riscv32-".to_owned() + - clang_target.strip_prefix("riscv32imc-").unwrap(); + const TRIPLE_HYPHENS_MESSAGE: &str = "Target triple should contain hyphens"; + + let mut triple: Vec<&str> = rust_target.split_terminator('-').collect(); + + assert!(!triple.is_empty(), "{}", TRIPLE_HYPHENS_MESSAGE); + triple.resize(4, ""); + + // RISC-V + if triple[0].starts_with("riscv32") { + triple[0] = "riscv32"; + } else if triple[0].starts_with("riscv64") { + triple[0] = "riscv64"; + } + + // Apple + if triple[1] == "apple" { + if triple[0] == "aarch64" { + triple[0] = "arm64"; + } + if triple[3] == "sim" { + triple[3] = "simulator"; } - return clang_target.into(); - } else if rust_target.starts_with("riscv32imc-") { - let mut clang_target = "riscv32-".to_owned(); - clang_target.push_str(rust_target.strip_prefix("riscv32imc-").unwrap()); - return clang_target.into(); - } else if rust_target.starts_with("riscv32imac-") { - let mut clang_target = "riscv32-".to_owned(); - clang_target - .push_str(rust_target.strip_prefix("riscv32imac-").unwrap()); - return clang_target.into(); - } else if rust_target.starts_with("riscv32imafc-") { - let mut clang_target = "riscv32-".to_owned(); - clang_target - .push_str(rust_target.strip_prefix("riscv32imafc-").unwrap()); - return clang_target.into(); } - rust_target.into() + + // ESP-IDF + if triple[2] == "espidf" { + triple[2] = "elf"; + } + + triple + .iter() + .skip(1) + .fold(triple[0].to_string(), |triple, part| { + if part.is_empty() { + triple + } else { + triple + "-" + part + } + }) + .into() } /// Returns the effective target, and whether it was explicitly specified on the @@ -757,10 +754,22 @@ impl Bindings { /// Generate bindings for the given options. pub(crate) fn generate( mut options: BindgenOptions, - input_unsaved_files: Vec, + input_unsaved_files: &[clang::UnsavedFile], ) -> Result { ensure_libclang_is_loaded(); + #[cfg(feature = "runtime")] + match clang_sys::get_library().unwrap().version() { + None => { + warn!("Could not detect a Clang version, make sure you are using libclang 9 or newer"); + } + Some(version) => { + if version < clang_sys::Version::V9_0 { + warn!("Detected Clang version {version:?} which is unsupported and can cause invalid code generation, use libclang 9 or newer"); + } + } + } + #[cfg(feature = "runtime")] debug!( "Generating bindings, libclang at {}", @@ -785,9 +794,9 @@ impl Bindings { if !explicit_target && !is_host_build { options.clang_args.insert( 0, - format!("--target={}", effective_target).into_boxed_str(), + format!("--target={effective_target}").into_boxed_str(), ); - }; + } fn detect_include_paths(options: &mut BindgenOptions) { if !options.detect_include_paths { @@ -829,8 +838,7 @@ impl Bindings { }; debug!( - "Trying to find clang with flags: {:?}", - clang_args_for_clang_sys + "Trying to find clang with flags: {clang_args_for_clang_sys:?}" ); let clang = match clang_sys::support::Clang::find( @@ -841,7 +849,7 @@ impl Bindings { Some(clang) => clang, }; - debug!("Found clang: {:?}", clang); + debug!("Found clang: {clang:?}"); // Whether we are working with C or C++ inputs. let is_cpp = args_are_cpp(&options.clang_args) || @@ -854,7 +862,7 @@ impl Bindings { }; if let Some(search_paths) = search_paths { - for path in search_paths.into_iter() { + for path in search_paths { if let Ok(path) = path.into_os_string().into_string() { options.clang_args.push("-isystem".into()); options.clang_args.push(path.into_boxed_str()); @@ -897,21 +905,19 @@ impl Bindings { if idx != 0 || !options.input_headers.is_empty() { options.clang_args.push("-include".into()); } - options.clang_args.push(f.name.to_str().unwrap().into()) + options.clang_args.push(f.name.to_str().unwrap().into()); } - debug!("Fixed-up options: {:?}", options); + debug!("Fixed-up options: {options:?}"); let time_phases = options.time_phases; - let mut context = BindgenContext::new(options, &input_unsaved_files); + let mut context = BindgenContext::new(options, input_unsaved_files); if is_host_build { debug_assert_eq!( context.target_pointer_size(), - std::mem::size_of::<*mut ()>(), - "{:?} {:?}", - effective_target, - HOST_TARGET + size_of::<*mut ()>(), + "{effective_target:?} {HOST_TARGET:?}" ); } @@ -944,13 +950,13 @@ impl Bindings { if !self.options.disable_header_comment { let version = option_env!("CARGO_PKG_VERSION").unwrap_or("(unknown version)"); - writeln!( + write!( writer, - "/* automatically generated by rust-bindgen {version} */{NL}", + "/* automatically generated by rust-bindgen {version} */{NL}{NL}", )?; } - for line in self.options.raw_lines.iter() { + for line in &self.options.raw_lines { writer.write_all(line.as_bytes())?; writer.write_all(NL.as_bytes())?; } @@ -965,8 +971,7 @@ impl Bindings { } Err(err) => { eprintln!( - "Failed to run rustfmt: {} (non-fatal, continuing)", - err + "Failed to run rustfmt: {err} (non-fatal, continuing)" ); writer.write_all(self.module.to_string().as_bytes())?; } @@ -983,14 +988,6 @@ impl Bindings { if let Ok(rustfmt) = env::var("RUSTFMT") { return Ok(Cow::Owned(rustfmt.into())); } - #[cfg(feature = "which-rustfmt")] - match which::which("rustfmt") { - Ok(p) => Ok(Cow::Owned(p)), - Err(e) => { - Err(io::Error::new(io::ErrorKind::Other, format!("{}", e))) - } - } - #[cfg(not(feature = "which-rustfmt"))] // No rustfmt binary was specified, so assume that the binary is called // "rustfmt" and that it is in the user's PATH. Ok(Cow::Owned("rustfmt".into())) @@ -1027,6 +1024,12 @@ impl Bindings { cmd.args(["--config-path", path]); } + let edition = self + .options + .rust_edition + .unwrap_or_else(|| self.options.rust_target.latest_edition()); + cmd.args(["--edition", &format!("{edition}")]); + let mut child = cmd.spawn()?; let mut child_stdin = child.stdin.take().unwrap(); let mut child_stdout = child.stdout.take().unwrap(); @@ -1075,14 +1078,14 @@ impl Bindings { } fn rustfmt_non_fatal_error_diagnostic(msg: &str, _options: &BindgenOptions) { - warn!("{}", msg); + warn!("{msg}"); #[cfg(feature = "experimental")] if _options.emit_diagnostics { use crate::diagnostics::{Diagnostic, Level}; Diagnostic::default() - .with_title(msg, Level::Warn) + .with_title(msg, Level::Warning) .add_annotation( "The bindings will be generated but not formatted.", Level::Note, @@ -1134,7 +1137,7 @@ fn parse(context: &mut BindgenContext) -> Result<(), BindgenError> { use clang_sys::*; let mut error = None; - for d in context.translation_unit().diags().iter() { + for d in &context.translation_unit().diags() { let msg = d.format(); let is_err = d.severity() >= CXDiagnostic_Error; if is_err { @@ -1142,7 +1145,7 @@ fn parse(context: &mut BindgenContext) -> Result<(), BindgenError> { error.push_str(&msg); error.push('\n'); } else { - eprintln!("clang diag: {}", msg); + eprintln!("clang diag: {msg}"); } } @@ -1154,10 +1157,10 @@ fn parse(context: &mut BindgenContext) -> Result<(), BindgenError> { if context.options().emit_ast { fn dump_if_not_builtin(cur: &clang::Cursor) -> CXChildVisitResult { - if !cur.is_builtin() { - clang::ast_dump(cur, 0) - } else { + if cur.is_builtin() { CXChildVisit_Continue + } else { + clang::ast_dump(cur, 0) } } cursor.visit(|cur| dump_if_not_builtin(&cur)); @@ -1165,11 +1168,12 @@ fn parse(context: &mut BindgenContext) -> Result<(), BindgenError> { let root = context.root_module(); context.with_module(root, |ctx| { - cursor.visit_sorted(ctx, |ctx, child| parse_one(ctx, child, None)) + cursor.visit_sorted(ctx, |ctx, child| parse_one(ctx, child, None)); }); - assert!( - context.current_module() == context.root_module(), + assert_eq!( + context.current_module(), + context.root_module(), "How did this happen?" ); Ok(()) @@ -1192,7 +1196,7 @@ pub fn clang_version() -> ClangVersion { let raw_v: String = clang::extract_clang_version(); let split_v: Option> = raw_v .split_whitespace() - .find(|t| t.chars().next().map_or(false, |v| v.is_ascii_digit())) + .find(|t| t.chars().next().is_some_and(|v| v.is_ascii_digit())) .map(|v| v.split('.').collect()); if let Some(v) = split_v { if v.len() >= 2 { @@ -1205,7 +1209,7 @@ pub fn clang_version() -> ClangVersion { }; } } - }; + } ClangVersion { parsed: None, full: raw_v.clone(), @@ -1215,11 +1219,11 @@ pub fn clang_version() -> ClangVersion { fn env_var + AsRef>( parse_callbacks: &[Rc], key: K, -) -> Result { +) -> Result { for callback in parse_callbacks { callback.read_env_var(key.as_ref()); } - std::env::var(key) + env::var(key) } /// Looks for the env var `var_${TARGET}`, and falls back to just `var` when it is not found. @@ -1228,12 +1232,12 @@ fn get_target_dependent_env_var( var: &str, ) -> Option { if let Ok(target) = env_var(parse_callbacks, "TARGET") { - if let Ok(v) = env_var(parse_callbacks, format!("{}_{}", var, target)) { + if let Ok(v) = env_var(parse_callbacks, format!("{var}_{target}")) { return Some(v); } if let Ok(v) = env_var( parse_callbacks, - format!("{}_{}", var, target.replace('-', "_")), + format!("{var}_{}", target.replace('-', "_")), ) { return Some(v); } @@ -1242,7 +1246,7 @@ fn get_target_dependent_env_var( env_var(parse_callbacks, var).ok() } -/// A ParseCallbacks implementation that will act on file includes by echoing a rerun-if-changed +/// A `ParseCallbacks` implementation that will act on file includes by echoing a rerun-if-changed /// line and on env variable usage by echoing a rerun-if-env-changed line /// /// When running inside a `build.rs` script, this can be used to make cargo invalidate the @@ -1295,24 +1299,24 @@ impl Default for CargoCallbacks { impl callbacks::ParseCallbacks for CargoCallbacks { fn header_file(&self, filename: &str) { if self.rerun_on_header_files { - println!("cargo:rerun-if-changed={}", filename); + println!("cargo:rerun-if-changed={filename}"); } } fn include_file(&self, filename: &str) { - println!("cargo:rerun-if-changed={}", filename); + println!("cargo:rerun-if-changed={filename}"); } fn read_env_var(&self, key: &str) { - println!("cargo:rerun-if-env-changed={}", key); + println!("cargo:rerun-if-env-changed={key}"); } } -/// Test command_line_flag function. +/// Test `command_line_flag` function. #[test] fn commandline_flag_unit_test_function() { //Test 1 - let bindings = crate::builder(); + let bindings = builder(); let command_line_flags = bindings.command_line_flags(); let test_cases = [ @@ -1328,7 +1332,7 @@ fn commandline_flag_unit_test_function() { assert!(test_cases.iter().all(|x| command_line_flags.contains(x))); //Test 2 - let bindings = crate::builder() + let bindings = builder() .header("input_header") .allowlist_type("Distinct_Type") .allowlist_function("safe_function"); @@ -1348,7 +1352,7 @@ fn commandline_flag_unit_test_function() { .iter() .map(|&x| x.into()) .collect::>(); - println!("{:?}", command_line_flags); + println!("{command_line_flags:?}"); assert!(test_cases.iter().all(|x| command_line_flags.contains(x))); } @@ -1383,6 +1387,10 @@ fn test_rust_to_clang_target_riscv() { rust_to_clang_target("riscv32imafc-unknown-none-elf").as_ref(), "riscv32-unknown-none-elf" ); + assert_eq!( + rust_to_clang_target("riscv32i-unknown-none-elf").as_ref(), + "riscv32-unknown-none-elf" + ); } #[test] @@ -1396,3 +1404,19 @@ fn test_rust_to_clang_target_espidf() { "xtensa-esp32-elf" ); } + +#[test] +fn test_rust_to_clang_target_simulator() { + assert_eq!( + rust_to_clang_target("aarch64-apple-ios-sim").as_ref(), + "arm64-apple-ios-simulator" + ); + assert_eq!( + rust_to_clang_target("aarch64-apple-tvos-sim").as_ref(), + "arm64-apple-tvos-simulator" + ); + assert_eq!( + rust_to_clang_target("aarch64-apple-watchos-sim").as_ref(), + "arm64-apple-watchos-simulator" + ); +} diff --git a/bindgen/log_stubs.rs b/bindgen/log_stubs.rs index 8315983128..51d2f81fd1 100644 --- a/bindgen/log_stubs.rs +++ b/bindgen/log_stubs.rs @@ -1,5 +1,6 @@ #![allow(unused)] +#[clippy::format_args] macro_rules! log { (target: $target:expr, $lvl:expr, $($arg:tt)+) => {{ let _ = $target; @@ -10,22 +11,27 @@ macro_rules! log { let _ = format_args!($($arg)+); }}; } +#[clippy::format_args] macro_rules! error { (target: $target:expr, $($arg:tt)+) => { log!(target: $target, "", $($arg)+) }; ($($arg:tt)+) => { log!("", $($arg)+) }; } +#[clippy::format_args] macro_rules! warn { (target: $target:expr, $($arg:tt)*) => { log!(target: $target, "", $($arg)*) }; ($($arg:tt)*) => { log!("", $($arg)*) }; } +#[clippy::format_args] macro_rules! info { (target: $target:expr, $($arg:tt)+) => { log!(target: $target, "", $($arg)+) }; ($($arg:tt)+) => { log!("", $($arg)+) }; } +#[clippy::format_args] macro_rules! debug { (target: $target:expr, $($arg:tt)+) => { log!(target: $target, "", $($arg)+) }; ($($arg:tt)+) => { log!("", $($arg)+) }; } +#[clippy::format_args] macro_rules! trace { (target: $target:expr, $($arg:tt)+) => { log!(target: $target, "", $($arg)+) }; ($($arg:tt)+) => { log!("", $($arg)+) }; diff --git a/bindgen/options/as_args.rs b/bindgen/options/as_args.rs index 6918ad9fec..83103fdaf4 100644 --- a/bindgen/options/as_args.rs +++ b/bindgen/options/as_args.rs @@ -1,6 +1,6 @@ use std::path::PathBuf; -use crate::RegexSet; +use crate::regex_set::RegexSet; /// Trait used to turn [`crate::BindgenOptions`] fields into CLI args. pub(super) trait AsArgs { diff --git a/bindgen-cli/options.rs b/bindgen/options/cli.rs similarity index 60% rename from bindgen-cli/options.rs rename to bindgen/options/cli.rs index 66bb3f1439..d3cf5d0916 100644 --- a/bindgen-cli/options.rs +++ b/bindgen/options/cli.rs @@ -1,24 +1,37 @@ -use bindgen::callbacks::TypeKind; -use bindgen::{ - builder, Abi, AliasVariation, Builder, CodegenConfig, EnumVariation, +#![allow(unused_qualifications)] // Clap somehow generates a lot of these + +use crate::{ + builder, + callbacks::{ + AttributeInfo, DeriveInfo, ItemInfo, ParseCallbacks, TypeKind, + }, + features::{RustEdition, EARLIEST_STABLE_RUST}, + regex_set::RegexSet, + Abi, AliasVariation, Builder, CodegenConfig, EnumVariation, FieldVisibilityKind, Formatter, MacroTypeVariation, NonCopyUnionStyle, - RegexSet, RustTarget, DEFAULT_ANON_FIELDS_PREFIX, RUST_TARGET_STRINGS, + RustTarget, }; -use clap::error::{Error, ErrorKind}; -use clap::{CommandFactory, Parser}; -use std::fs::File; +use clap::{ + error::{Error, ErrorKind}, + CommandFactory, Parser, +}; +use proc_macro2::TokenStream; use std::io; use std::path::{Path, PathBuf}; -use std::process::exit; +use std::str::FromStr; +use std::{fs::File, process::exit}; fn rust_target_help() -> String { format!( - "Version of the Rust compiler to target. Valid options are: {:?}. Defaults to {}.", - RUST_TARGET_STRINGS, + "Version of the Rust compiler to target. Any Rust version after {EARLIEST_STABLE_RUST} is supported. Defaults to {}.", RustTarget::default() ) } +fn rust_edition_help() -> String { + format!("Rust edition to target. Defaults to the latest edition supported by the chosen Rust target. Possible values: ({}). ", RustEdition::ALL.map(|e| e.to_string()).join("|")) +} + fn parse_codegen_config( what_to_generate: &str, ) -> Result { @@ -34,7 +47,7 @@ fn parse_codegen_config( otherwise => { return Err(Error::raw( ErrorKind::InvalidValue, - format!("Unknown codegen item kind: {}", otherwise), + format!("Unknown codegen item kind: {otherwise}"), )); } } @@ -87,12 +100,50 @@ fn parse_custom_derive( Ok((derives, regex.to_owned())) } +fn parse_custom_attribute( + custom_attribute: &str, +) -> Result<(Vec, String), Error> { + let mut brace_level = 0; + let (regex, attributes) = custom_attribute + .rsplit_once(|c| { + match c { + ']' => brace_level += 1, + '[' => brace_level -= 1, + _ => {} + } + c == '=' && brace_level == 0 + }) + .ok_or_else(|| Error::raw(ErrorKind::InvalidValue, "Missing `=`"))?; + + let mut brace_level = 0; + let attributes = attributes + .split(|c| { + match c { + ']' => brace_level += 1, + '[' => brace_level -= 1, + _ => {} + } + c == ',' && brace_level == 0 + }) + .map(|s| s.to_owned()) + .collect::>(); + + for attribute in &attributes { + if let Err(err) = TokenStream::from_str(attribute) { + return Err(Error::raw(ErrorKind::InvalidValue, err)); + } + } + + Ok((attributes, regex.to_owned())) +} + #[derive(Parser, Debug)] #[clap( about = "Generates Rust bindings from C/C++ headers.", override_usage = "bindgen
-- ...", trailing_var_arg = true )] +#[allow(clippy::doc_markdown)] struct BindgenCommand { /// C or C++ header file. header: Option, @@ -114,6 +165,9 @@ struct BindgenCommand { /// Mark any enum whose name matches REGEX as a Rust enum. #[arg(long, value_name = "REGEX")] rustified_enum: Vec, + /// Mark any enum whose name matches REGEX as a non-exhaustive Rust enum. + #[arg(long, value_name = "REGEX")] + rustified_non_exhaustive_enum: Vec, /// Mark any enum whose name matches REGEX as a series of constants. #[arg(long, value_name = "REGEX")] constified_enum: Vec, @@ -223,8 +277,8 @@ struct BindgenCommand { #[arg(long, value_name = "PREFIX")] ctypes_prefix: Option, /// Use the given PREFIX for anonymous fields. - #[arg(long, default_value = DEFAULT_ANON_FIELDS_PREFIX, value_name = "PREFIX")] - anon_fields_prefix: String, + #[arg(long, value_name = "PREFIX")] + anon_fields_prefix: Option, /// Time the different bindgen phases and print to stderr #[arg(long)] time_phases: bool, @@ -287,6 +341,8 @@ struct BindgenCommand { module_raw_line: Vec, #[arg(long, help = rust_target_help())] rust_target: Option, + #[arg(long, value_name = "EDITION", help = rust_edition_help())] + rust_edition: Option, /// Use types from Rust core instead of std. #[arg(long)] use_core: bool, @@ -373,7 +429,7 @@ struct BindgenCommand { /// Prefix the name of exported symbols. #[arg(long)] prefix_link_name: Option, - /// Makes generated bindings `pub` only for items if the items are publically accessible in C++. + /// Makes generated bindings `pub` only for items if the items are publicly accessible in C++. #[arg(long)] respect_cxx_access_specs: bool, /// Always translate enum integer types to native Rust integer types. @@ -385,6 +441,15 @@ struct BindgenCommand { /// Always output explicit padding fields. #[arg(long)] explicit_padding: bool, + /// Always be specific about the 'receiver' of a virtual function. + #[arg(long)] + use_specific_virtual_function_receiver: bool, + /// Use distinct char16_t + #[arg(long)] + use_distinct_char16_t: bool, + /// Output C++ overloaded operators + #[arg(long)] + represent_cxx_operators: bool, /// Enables generation of vtable functions. #[arg(long)] vtable_generation: bool, @@ -400,6 +465,15 @@ struct BindgenCommand { /// Wrap unsafe operations in unsafe blocks. #[arg(long)] wrap_unsafe_ops: bool, + /// Enable fallback for clang macro parsing. + #[arg(long)] + clang_macro_fallback: bool, + /// Set path for temporary files generated by fallback for clang macro parsing. + #[arg(long)] + clang_macro_fallback_build_dir: Option, + /// Use DSTs to represent structures with flexible array members. + #[arg(long)] + flexarray_dst: bool, /// Derive custom traits on any kind of type. The CUSTOM value must be of the shape REGEX=DERIVE where DERIVE is a coma-separated list of derive macros. #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_derive)] with_derive_custom: Vec<(Vec, String)>, @@ -412,22 +486,47 @@ struct BindgenCommand { /// Derive custom traits on a `union`. The CUSTOM value must be of the shape REGEX=DERIVE where DERIVE is a coma-separated list of derive macros. #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_derive)] with_derive_custom_union: Vec<(Vec, String)>, + /// Add custom attributes on any kind of type. The CUSTOM value must be of the shape REGEX=ATTRIBUTE where ATTRIBUTE is a coma-separated list of attributes. + #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_attribute)] + with_attribute_custom: Vec<(Vec, String)>, + /// Add custom attributes on a `struct`. The CUSTOM value must be of the shape REGEX=ATTRIBUTE where ATTRIBUTE is a coma-separated list of attributes. + #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_attribute)] + with_attribute_custom_struct: Vec<(Vec, String)>, + /// Add custom attributes on an `enum. The CUSTOM value must be of the shape REGEX=ATTRIBUTE where ATTRIBUTE is a coma-separated list of attributes. + #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_attribute)] + with_attribute_custom_enum: Vec<(Vec, String)>, + /// Add custom attributes on a `union`. The CUSTOM value must be of the shape REGEX=ATTRIBUTE where ATTRIBUTE is a coma-separated list of attributes. + #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_attribute)] + with_attribute_custom_union: Vec<(Vec, String)>, /// Generate wrappers for `static` and `static inline` functions. - #[arg(long, requires = "experimental")] + #[arg(long)] wrap_static_fns: bool, /// Sets the PATH for the source file that must be created due to the presence of `static` and /// `static inline` functions. - #[arg(long, requires = "experimental", value_name = "PATH")] + #[arg(long, value_name = "PATH")] wrap_static_fns_path: Option, /// Sets the SUFFIX added to the extern wrapper functions generated for `static` and `static /// inline` functions. - #[arg(long, requires = "experimental", value_name = "SUFFIX")] + #[arg(long, value_name = "SUFFIX")] wrap_static_fns_suffix: Option, /// Set the default VISIBILITY of fields, including bitfields and accessor methods for /// bitfields. This flag is ignored if the `--respect-cxx-access-specs` flag is used. #[arg(long, value_name = "VISIBILITY")] default_visibility: Option, + /// Whether to generate C++ functions marked with "=delete" even though they + /// can't be called. + #[arg(long)] + generate_deleted_functions: bool, + /// Whether to generate C++ "pure virtual" functions even though they can't + /// be called. + #[arg(long)] + generate_pure_virtual_functions: bool, + /// Whether to generate C++ private functions even though they can't + /// be called. + #[arg(long)] + generate_private_functions: bool, /// Whether to emit diagnostics or not. + #[cfg(feature = "experimental")] #[arg(long, requires = "experimental")] emit_diagnostics: bool, /// Generates completions for the specified SHELL, sends them to `stdout` and exits. @@ -460,6 +559,7 @@ where newtype_enum, newtype_global_enum, rustified_enum, + rustified_non_exhaustive_enum, constified_enum, constified_enum_module, default_macro_constant_type, @@ -518,6 +618,7 @@ where raw_line, module_raw_line, rust_target, + rust_edition, use_core, conservative_inline_namespaces, allowlist_function, @@ -549,19 +650,33 @@ where translate_enum_integer_types, c_naming, explicit_padding, + use_specific_virtual_function_receiver, + use_distinct_char16_t, + represent_cxx_operators, vtable_generation, sort_semantically, merge_extern_blocks, override_abi, wrap_unsafe_ops, + clang_macro_fallback, + clang_macro_fallback_build_dir, + flexarray_dst, with_derive_custom, with_derive_custom_struct, with_derive_custom_enum, with_derive_custom_union, + with_attribute_custom, + with_attribute_custom_struct, + with_attribute_custom_enum, + with_attribute_custom_union, wrap_static_fns, wrap_static_fns_path, wrap_static_fns_suffix, default_visibility, + generate_deleted_functions, + generate_pure_virtual_functions, + generate_private_functions, + #[cfg(feature = "experimental")] emit_diagnostics, generate_shell_completions, experimental: _, @@ -574,10 +689,10 @@ where shell, &mut BindgenCommand::command(), "bindgen", - &mut std::io::stdout(), + &mut io::stdout(), ); - exit(0); + exit(0) } if version { @@ -586,269 +701,278 @@ where option_env!("CARGO_PKG_VERSION").unwrap_or("unknown") ); if verbose { - println!("Clang: {}", bindgen::clang_version().full); + println!("Clang: {}", crate::clang_version().full); } - std::process::exit(0); - } - - let mut builder = builder(); - - if let Some(header) = header { - builder = builder.header(header); - } else { - return Err(io::Error::new(io::ErrorKind::Other, "Header not found")); - } - - if let Some(rust_target) = rust_target { - builder = builder.rust_target(rust_target); - } - - if let Some(variant) = default_enum_style { - builder = builder.default_enum_style(variant); - } - - for regex in bitfield_enum { - builder = builder.bitfield_enum(regex); - } - - for regex in newtype_enum { - builder = builder.newtype_enum(regex); - } - - for regex in newtype_global_enum { - builder = builder.newtype_global_enum(regex); - } - - for regex in rustified_enum { - builder = builder.rustified_enum(regex); - } - - for regex in constified_enum { - builder = builder.constified_enum(regex); - } - - for regex in constified_enum_module { - builder = builder.constified_enum_module(regex); - } - - if let Some(default_macro_constant_type) = default_macro_constant_type { - builder = - builder.default_macro_constant_type(default_macro_constant_type) - } - - if let Some(variant) = default_alias_style { - builder = builder.default_alias_style(variant); - } - - for regex in normal_alias { - builder = builder.type_alias(regex); - } - - for regex in new_type_alias { - builder = builder.new_type_alias(regex); - } - - for regex in new_type_alias_deref { - builder = builder.new_type_alias_deref(regex); - } - - if let Some(variant) = default_non_copy_union_style { - builder = builder.default_non_copy_union_style(variant); - } - - for regex in bindgen_wrapper_union { - builder = builder.bindgen_wrapper_union(regex); - } - - for regex in manually_drop_union { - builder = builder.manually_drop_union(regex); - } - - for ty in blocklist_type { - builder = builder.blocklist_type(ty); - } - - for fun in blocklist_function { - builder = builder.blocklist_function(fun); - } - - for id in blocklist_item { - builder = builder.blocklist_item(id); - } - - for file in blocklist_file { - builder = builder.blocklist_file(file); - } - - for var in blocklist_var { - builder = builder.blocklist_var(var); - } - - if builtins { - builder = builder.emit_builtins(); - } - - if no_layout_tests { - builder = builder.layout_tests(false); - } - - if no_derive_copy { - builder = builder.derive_copy(false); - } - if no_derive_debug { - builder = builder.derive_debug(false); + exit(0) } - if impl_debug { - builder = builder.impl_debug(true); - } - - if impl_partialeq { - builder = builder.impl_partialeq(true); - } - - if with_derive_default { - builder = builder.derive_default(true); - } - - if with_derive_hash { - builder = builder.derive_hash(true); - } - - if with_derive_partialeq { - builder = builder.derive_partialeq(true); - } - - if with_derive_partialord { - builder = builder.derive_partialord(true); - } - - if with_derive_eq { - builder = builder.derive_eq(true); - } - - if with_derive_ord { - builder = builder.derive_ord(true); - } - - if no_derive_default { - builder = builder.derive_default(false); - } - - if no_prepend_enum_name { - builder = builder.prepend_enum_name(false); - } - - if no_include_path_detection { - builder = builder.detect_include_paths(false); - } - - if fit_macro_constant_types { - builder = builder.fit_macro_constants(true); - } - - if time_phases { - builder = builder.time_phases(true); - } - - if use_array_pointers_in_arguments { - builder = builder.array_pointers_in_arguments(true); - } - - if let Some(wasm_import_name) = wasm_import_module_name { - builder = builder.wasm_import_module_name(wasm_import_name); - } - - if let Some(prefix) = ctypes_prefix { - builder = builder.ctypes_prefix(prefix); - } - - builder = builder.anon_fields_prefix(anon_fields_prefix); - - if let Some(config) = generate { - builder = builder.with_codegen_config(config); - } - - if emit_clang_ast { - builder = builder.emit_clang_ast(); + if header.is_none() { + return Err(io::Error::new(io::ErrorKind::Other, "Header not found")); } - if emit_ir { - builder = builder.emit_ir(); - } + let mut builder = builder(); - if let Some(path) = emit_ir_graphviz { - builder = builder.emit_ir_graphviz(path); + #[derive(Debug)] + struct PrefixLinkNameCallback { + prefix: String, } - if enable_cxx_namespaces { - builder = builder.enable_cxx_namespaces(); + impl ParseCallbacks for PrefixLinkNameCallback { + fn generated_link_name_override( + &self, + item_info: ItemInfo<'_>, + ) -> Option { + let mut prefix = self.prefix.clone(); + prefix.push_str(item_info.name); + Some(prefix) + } } - if enable_function_attribute_detection { - builder = builder.enable_function_attribute_detection(); + #[derive(Debug)] + struct CustomDeriveCallback { + derives: Vec, + kind: Option, + regex_set: RegexSet, } - if disable_name_namespacing { - builder = builder.disable_name_namespacing(); - } + impl ParseCallbacks for CustomDeriveCallback { + fn cli_args(&self) -> Vec { + let mut args = vec![]; - if disable_nested_struct_naming { - builder = builder.disable_nested_struct_naming(); - } + let flag = match &self.kind { + None => "--with-derive-custom", + Some(TypeKind::Struct) => "--with-derive-custom-struct", + Some(TypeKind::Enum) => "--with-derive-custom-enum", + Some(TypeKind::Union) => "--with-derive-custom-union", + }; - if disable_untagged_union { - builder = builder.disable_untagged_union(); - } + let derives = self.derives.join(","); - if disable_header_comment { - builder = builder.disable_header_comment(); - } + for item in self.regex_set.get_items() { + args.extend_from_slice(&[ + flag.to_owned(), + format!("{item}={derives}"), + ]); + } - if ignore_functions { - builder = builder.ignore_functions(); - } + args + } - if ignore_methods { - builder = builder.ignore_methods(); + fn add_derives(&self, info: &DeriveInfo<'_>) -> Vec { + if self.kind.map_or(true, |kind| kind == info.kind) && + self.regex_set.matches(info.name) + { + return self.derives.clone(); + } + vec![] + } } - if no_convert_floats { - builder = builder.no_convert_floats(); + #[derive(Debug)] + struct CustomAttributeCallback { + attributes: Vec, + kind: Option, + regex_set: RegexSet, } - if no_doc_comments { - builder = builder.generate_comments(false); - } + impl ParseCallbacks for CustomAttributeCallback { + fn cli_args(&self) -> Vec { + let mut args = vec![]; - if no_recursive_allowlist { - builder = builder.allowlist_recursively(false); - } + let flag = match &self.kind { + None => "--with-attribute-custom", + Some(TypeKind::Struct) => "--with-attribute-custom-struct", + Some(TypeKind::Enum) => "--with-attribute-custom-enum", + Some(TypeKind::Union) => "--with-attribute-custom-union", + }; - if objc_extern_crate { - builder = builder.objc_extern_crate(true); - } + let attributes = self.attributes.join(","); - if generate_block { - builder = builder.generate_block(true); - } + for item in self.regex_set.get_items() { + args.extend_from_slice(&[ + flag.to_owned(), + format!("{item}={attributes}"), + ]); + } - if generate_cstr { - builder = builder.generate_cstr(true); - } + args + } - if block_extern_crate { - builder = builder.block_extern_crate(true); + fn add_attributes(&self, info: &AttributeInfo<'_>) -> Vec { + if self.kind.map_or(true, |kind| kind == info.kind) && + self.regex_set.matches(info.name) + { + return self.attributes.clone(); + } + vec![] + } } - for ty in opaque_type { - builder = builder.opaque_type(ty); + /// Macro used to apply CLI arguments to a builder. + /// + /// This is done by passing an identifier for each argument and a function to be applied over + /// the builder. For example: + /// ```rust,ignore + /// fn apply_arg(builder: Builder, arg_value: Value) -> Builder { + /// todo!() + /// } + /// + /// apply_args!( + /// builder { + /// arg => apply_arg, + /// } + /// ); + /// ``` + /// + /// If the identifier of the argument is the same as an already existing builder method then + /// you can omit the second part: + /// ```rust,ignore + /// apply_args!( + /// builder { + /// arg + /// } + /// ); + /// ``` + /// Which expands to the same code as: + /// ```rust,ignore + /// apply_args!( + /// builder { + /// arg => Builder::arg, + /// } + /// ); + /// ``` + macro_rules! apply_args { + ($builder:ident {}) => { $builder }; + ($builder:ident {$arg:ident => $function:expr, $($token:tt)*}) => { + { + $builder = CliArg::apply($arg, $builder, $function); + apply_args!($builder {$($token)*}) + } + }; + ($builder:ident {$arg:ident, $($token:tt)*}) => { + { + $builder = CliArg::apply($arg, $builder, Builder::$arg); + apply_args!($builder {$($token)*}) + } + } } - for line in raw_line { - builder = builder.raw_line(line); - } + builder = apply_args!( + builder { + header, + rust_target, + rust_edition, + default_enum_style, + bitfield_enum, + newtype_enum, + newtype_global_enum, + rustified_enum, + rustified_non_exhaustive_enum, + constified_enum, + constified_enum_module, + default_macro_constant_type, + default_alias_style, + normal_alias => Builder::type_alias, + new_type_alias, + new_type_alias_deref, + default_non_copy_union_style, + bindgen_wrapper_union, + manually_drop_union, + blocklist_type, + blocklist_function, + blocklist_item, + blocklist_file, + blocklist_var, + builtins => |b, _| b.emit_builtins(), + no_layout_tests => |b, _| b.layout_tests(false), + no_derive_copy => |b, _| b.derive_copy(false), + no_derive_debug => |b, _| b.derive_debug(false), + impl_debug, + impl_partialeq, + with_derive_default => Builder::derive_default, + with_derive_hash => Builder::derive_hash, + with_derive_partialeq => Builder::derive_partialeq, + with_derive_partialord => Builder::derive_partialord, + with_derive_eq => Builder::derive_eq, + with_derive_ord => Builder::derive_ord, + no_derive_default => |b, _| b.derive_default(false), + no_prepend_enum_name => |b, _| b.prepend_enum_name(false), + no_include_path_detection => |b, _| b.detect_include_paths(false), + fit_macro_constant_types => Builder::fit_macro_constants, + time_phases, + use_array_pointers_in_arguments => Builder::array_pointers_in_arguments, + wasm_import_module_name, + ctypes_prefix, + anon_fields_prefix, + generate => Builder::with_codegen_config, + emit_clang_ast => |b, _| b.emit_clang_ast(), + emit_ir => |b, _| b.emit_ir(), + emit_ir_graphviz, + enable_cxx_namespaces => |b, _| b.enable_cxx_namespaces(), + enable_function_attribute_detection => |b, _| b.enable_function_attribute_detection(), + disable_name_namespacing => |b, _| b.disable_name_namespacing(), + disable_nested_struct_naming => |b, _| b.disable_nested_struct_naming(), + disable_untagged_union => |b, _| b.disable_untagged_union(), + disable_header_comment => |b, _| b.disable_header_comment(), + ignore_functions => |b, _| b.ignore_functions(), + ignore_methods => |b, _| b.ignore_methods(), + no_convert_floats => |b, _| b.no_convert_floats(), + no_doc_comments => |b, _| b.generate_comments(false), + no_recursive_allowlist => |b, _| b.allowlist_recursively(false), + objc_extern_crate, + generate_block, + generate_cstr, + block_extern_crate, + opaque_type, + raw_line, + use_core => |b, _| b.use_core(), + distrust_clang_mangling => |b, _| b.trust_clang_mangling(false), + conservative_inline_namespaces => |b, _| b.conservative_inline_namespaces(), + generate_inline_functions, + allowlist_function, + allowlist_type, + allowlist_var, + allowlist_file, + allowlist_item, + clang_args => Builder::clang_arg, + no_record_matches => |b, _| b.record_matches(false), + no_size_t_is_usize => |b, _| b.size_t_is_usize(false), + no_rustfmt_bindings => |b, _| b.formatter(Formatter::None), + formatter, + no_partialeq, + no_copy, + no_debug, + no_default, + no_hash, + must_use_type, + dynamic_loading => Builder::dynamic_library_name, + dynamic_link_require_all, + prefix_link_name => |b, prefix| b.parse_callbacks(Box::new(PrefixLinkNameCallback { prefix })), + respect_cxx_access_specs, + translate_enum_integer_types, + c_naming, + explicit_padding, + use_specific_virtual_function_receiver, + use_distinct_char16_t, + represent_cxx_operators, + vtable_generation, + sort_semantically, + merge_extern_blocks, + override_abi => |b, (abi, regex)| b.override_abi(abi, regex), + wrap_unsafe_ops, + clang_macro_fallback => |b, _| b.clang_macro_fallback(), + clang_macro_fallback_build_dir, + flexarray_dst, + wrap_static_fns, + wrap_static_fns_path, + wrap_static_fns_suffix, + default_visibility, + generate_deleted_functions, + generate_pure_virtual_functions, + generate_private_functions, + } + ); let mut values = module_raw_line.into_iter(); while let Some(module) = values.next() { @@ -856,46 +980,6 @@ where builder = builder.module_raw_line(module, line); } - if use_core { - builder = builder.use_core(); - } - - if distrust_clang_mangling { - builder = builder.trust_clang_mangling(false); - } - - if conservative_inline_namespaces { - builder = builder.conservative_inline_namespaces(); - } - - if generate_inline_functions { - builder = builder.generate_inline_functions(true); - } - - for regex in allowlist_function { - builder = builder.allowlist_function(regex); - } - - for regex in allowlist_type { - builder = builder.allowlist_type(regex); - } - - for regex in allowlist_var { - builder = builder.allowlist_var(regex); - } - - for file in allowlist_file { - builder = builder.allowlist_file(file); - } - - for item in allowlist_item { - builder = builder.allowlist_item(item); - } - - for arg in clang_args { - builder = builder.clang_arg(arg); - } - let output = if let Some(path) = &output { let file = File::create(path)?; if let Some(depfile) = depfile { @@ -913,160 +997,11 @@ where builder.dump_preprocessed_input()?; } - if no_record_matches { - builder = builder.record_matches(false); - } - - if no_size_t_is_usize { - builder = builder.size_t_is_usize(false); - } - - if no_rustfmt_bindings { - builder = builder.formatter(Formatter::None); - } - - if let Some(formatter) = formatter { - builder = builder.formatter(formatter); - } - if let Some(path) = rustfmt_configuration_file { builder = builder.rustfmt_configuration_file(Some(path)); } - for regex in no_partialeq { - builder = builder.no_partialeq(regex); - } - - for regex in no_copy { - builder = builder.no_copy(regex); - } - - for regex in no_debug { - builder = builder.no_debug(regex); - } - - for regex in no_default { - builder = builder.no_default(regex); - } - - for regex in no_hash { - builder = builder.no_hash(regex); - } - - for regex in must_use_type { - builder = builder.must_use_type(regex); - } - - if let Some(dynamic_library_name) = dynamic_loading { - builder = builder.dynamic_library_name(dynamic_library_name); - } - - if dynamic_link_require_all { - builder = builder.dynamic_link_require_all(true); - } - - if let Some(prefix_link_name) = prefix_link_name { - #[derive(Debug)] - struct PrefixLinkNameCallback { - prefix: String, - } - - impl bindgen::callbacks::ParseCallbacks for PrefixLinkNameCallback { - fn generated_link_name_override( - &self, - item_info: bindgen::callbacks::ItemInfo<'_>, - ) -> Option { - let mut prefix = self.prefix.clone(); - prefix.push_str(item_info.name); - Some(prefix) - } - } - - builder = builder.parse_callbacks(Box::new(PrefixLinkNameCallback { - prefix: prefix_link_name, - })) - } - - if respect_cxx_access_specs { - builder = builder.respect_cxx_access_specs(true); - } - - if translate_enum_integer_types { - builder = builder.translate_enum_integer_types(true); - } - - if c_naming { - builder = builder.c_naming(true); - } - - if explicit_padding { - builder = builder.explicit_padding(true); - } - - if vtable_generation { - builder = builder.vtable_generation(true); - } - - if sort_semantically { - builder = builder.sort_semantically(true); - } - - if merge_extern_blocks { - builder = builder.merge_extern_blocks(true); - } - - for (abi, regex) in override_abi { - builder = builder.override_abi(abi, regex); - } - - if wrap_unsafe_ops { - builder = builder.wrap_unsafe_ops(true); - } - - #[derive(Debug)] - struct CustomDeriveCallback { - derives: Vec, - kind: Option, - regex_set: bindgen::RegexSet, - } - - impl bindgen::callbacks::ParseCallbacks for CustomDeriveCallback { - fn cli_args(&self) -> Vec { - let mut args = vec![]; - - let flag = match &self.kind { - None => "--with-derive-custom", - Some(TypeKind::Struct) => "--with-derive-custom-struct", - Some(TypeKind::Enum) => "--with-derive-custom-enum", - Some(TypeKind::Union) => "--with-derive-custom-union", - }; - - let derives = self.derives.join(","); - - for item in self.regex_set.get_items() { - args.extend_from_slice(&[ - flag.to_owned(), - format!("{}={}", item, derives), - ]); - } - - args - } - - fn add_derives( - &self, - info: &bindgen::callbacks::DeriveInfo<'_>, - ) -> Vec { - if self.kind.map(|kind| kind == info.kind).unwrap_or(true) && - self.regex_set.matches(info.name) - { - return self.derives.clone(); - } - vec![] - } - } - - for (custom_derives, kind, name) in [ + for (custom_derives, kind, _name) in [ (with_derive_custom, None, "--with-derive-custom"), ( with_derive_custom_struct, @@ -1084,11 +1019,17 @@ where "--with-derive-custom-union", ), ] { - let name = emit_diagnostics.then_some(name); + #[cfg(feature = "experimental")] + let name = emit_diagnostics.then_some(_name); + for (derives, regex) in custom_derives { - let mut regex_set = RegexSet::new(); + let mut regex_set = RegexSet::default(); regex_set.insert(regex); + + #[cfg(feature = "experimental")] regex_set.build_with_diagnostics(false, name); + #[cfg(not(feature = "experimental"))] + regex_set.build(false); builder = builder.parse_callbacks(Box::new(CustomDeriveCallback { derives, @@ -1098,25 +1039,113 @@ where } } - if wrap_static_fns { - builder = builder.wrap_static_fns(true); - } - - if let Some(path) = wrap_static_fns_path { - builder = builder.wrap_static_fns_path(path); - } + for (custom_attributes, kind, _name) in [ + (with_attribute_custom, None, "--with-attribute-custom"), + ( + with_attribute_custom_struct, + Some(TypeKind::Struct), + "--with-attribute-custom-struct", + ), + ( + with_attribute_custom_enum, + Some(TypeKind::Enum), + "--with-attribute-custom-enum", + ), + ( + with_attribute_custom_union, + Some(TypeKind::Union), + "--with-attribute-custom-union", + ), + ] { + #[cfg(feature = "experimental")] + let name = emit_diagnostics.then_some(_name); - if let Some(suffix) = wrap_static_fns_suffix { - builder = builder.wrap_static_fns_suffix(suffix); - } + for (attributes, regex) in custom_attributes { + let mut regex_set = RegexSet::default(); + regex_set.insert(regex); - if let Some(visibility) = default_visibility { - builder = builder.default_visibility(visibility); + #[cfg(feature = "experimental")] + regex_set.build_with_diagnostics(false, name); + #[cfg(not(feature = "experimental"))] + regex_set.build(false); + + builder = + builder.parse_callbacks(Box::new(CustomAttributeCallback { + attributes, + kind, + regex_set, + })); + } } + #[cfg(feature = "experimental")] if emit_diagnostics { builder = builder.emit_diagnostics(); } Ok((builder, output, verbose)) } + +/// Trait for CLI arguments that can be applied to a [`Builder`]. +trait CliArg { + /// The value of this argument. + type Value; + + /// Apply the current argument to the passed [`Builder`]. + fn apply( + self, + builder: Builder, + f: impl Fn(Builder, Self::Value) -> Builder, + ) -> Builder; +} + +/// Boolean arguments are applied when they evaluate to `true`. +impl CliArg for bool { + type Value = bool; + + fn apply( + self, + mut builder: Builder, + f: impl Fn(Builder, Self::Value) -> Builder, + ) -> Builder { + if self { + builder = f(builder, self); + } + + builder + } +} + +/// Optional arguments are applied when they are `Some`. +impl CliArg for Option { + type Value = T; + + fn apply( + self, + mut builder: Builder, + f: impl Fn(Builder, Self::Value) -> Builder, + ) -> Builder { + if let Some(value) = self { + builder = f(builder, value); + } + + builder + } +} + +/// Multiple valued arguments are applied once for each value. +impl CliArg for Vec { + type Value = T; + + fn apply( + self, + mut builder: Builder, + f: impl Fn(Builder, Self::Value) -> Builder, + ) -> Builder { + for value in self { + builder = f(builder, value); + } + + builder + } +} diff --git a/bindgen/options/mod.rs b/bindgen/options/mod.rs index 6b5b4d8cbc..c9ef7c8b49 100644 --- a/bindgen/options/mod.rs +++ b/bindgen/options/mod.rs @@ -4,13 +4,15 @@ #[macro_use] mod helpers; mod as_args; +#[cfg(feature = "__cli")] +pub(crate) mod cli; use crate::callbacks::ParseCallbacks; use crate::codegen::{ AliasVariation, EnumVariation, MacroTypeVariation, NonCopyUnionStyle, }; use crate::deps::DepfileSpec; -use crate::features::{RustFeatures, RustTarget}; +use crate::features::{RustEdition, RustFeatures, RustTarget}; use crate::regex_set::RegexSet; use crate::Abi; use crate::Builder; @@ -21,9 +23,7 @@ use crate::HashMap; use crate::DEFAULT_ANON_FIELDS_PREFIX; use std::env; -#[cfg(feature = "experimental")] -use std::path::Path; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::rc::Rc; use as_args::AsArgs; @@ -37,20 +37,20 @@ use helpers::ignore; /// a block of code with the following items: /// /// - `default`: The default value for the field. If this item is omitted, `Default::default()` is -/// used instead, meaning that the type of the field must implement `Default`. +/// used instead, meaning that the type of the field must implement `Default`. /// - `methods`: A block of code containing methods for the `Builder` type. These methods should be -/// related to the field being declared. +/// related to the field being declared. /// - `as_args`: This item declares how the field should be converted into a valid CLI argument for -/// `bindgen` and is used in the [`Builder::command_line_flags`] method which is used to do a -/// roundtrip test of the CLI args in the `bindgen-test` crate. This item can take one of the -/// following: +/// `bindgen` and is used in the [`Builder::command_line_flags`] method which is used to do a +/// roundtrip test of the CLI args in the `bindgen-test` crate. This item can take one of the +/// following: /// - A string literal with the flag if the type of the field implements the [`AsArgs`] trait. /// - A closure with the signature `|field, args: &mut Vec| -> ()` that pushes arguments -/// into the `args` buffer based on the value of the field. This is used if the field does not -/// implement `AsArgs` or if the implementation of the trait is not logically correct for the -/// option and a custom behavior must be taken into account. +/// into the `args` buffer based on the value of the field. This is used if the field does not +/// implement `AsArgs` or if the implementation of the trait is not logically correct for the +/// option and a custom behavior must be taken into account. /// - The `ignore` literal, which does not emit any CLI arguments for this field. This is useful -/// if the field cannot be used from the `bindgen` CLI. +/// if the field cannot be used from the `bindgen` CLI. /// /// As an example, this would be the declaration of a `bool` field called `be_fun` whose default /// value is `false` (the `Default` value for `bool`): @@ -153,6 +153,64 @@ macro_rules! options { } options! { + /// Whether to specify the type of a virtual function receiver + use_specific_virtual_function_receiver: bool { + methods: { + /// Normally, virtual functions have void* as their 'this' type. + /// If this flag is enabled, override that behavior to indicate a + /// pointer of the specific type. + /// Disabled by default. + pub fn use_specific_virtual_function_receiver(mut self, doit: bool) -> Builder { + self.options.use_specific_virtual_function_receiver = doit; + self + } + }, + as_args: "--use-specific-virtual-function-receiver", + }, + + /// Whether we should distinguish between C++'s 'char16_t' and 'u16'. + /// The C++ type `char16_t` is its own special type; it's not a typedef + /// of some other integer (this differs from C). + /// As standard, bindgen represents C++ `char16_t` as `u16`. + /// Rust does not have a `std::os::raw::c_char16_t` type, and thus + /// we can't use a built-in Rust type in the generated bindings (and + /// nor would it be appropriate as it's a C++-specific type.) + /// But for some uses of bindgen, especially when downstream + /// post-processing occurs, it's important to distinguish `char16_t` + /// from normal `uint16_t`. When this option is enabled, bindgen + /// generates a fake type called `bindgen_cchar16_t`. Downstream + /// code post-processors should arrange to replace this with a + /// real type. + use_distinct_char16_t: bool { + methods: { + /// If this is true, denote 'char16_t' as a separate type from 'u16' + /// Disabled by default. + pub fn use_distinct_char16_t(mut self, doit: bool) -> Builder { + self.options.use_distinct_char16_t = doit; + self + } + }, + as_args: "--use-distinct-char16-t", + }, + /// Whether we should output C++ overloaded operators. By itself, + /// this option is not sufficient to produce valid output, because + /// such operators will have names that are not acceptable Rust + /// names (for example `operator=`). If you use this option, you'll also + /// have to rename the resulting functions - for example by using + /// [`ParseCallbacks::generated_name_override`]. + represent_cxx_operators: bool { + methods: { + /// If this is true, output existence of C++ overloaded operators. + /// At present, only operator= is noted. + /// Disabled by default. + pub fn represent_cxx_operators(mut self, doit: bool) -> Builder { + self.options.represent_cxx_operators = doit; + self + } + }, + as_args: "--represent-cxx-operators", + }, + /// Types that have been blocklisted and should not appear anywhere in the generated code. blocklisted_types: RegexSet { methods: { @@ -1143,7 +1201,7 @@ options! { }, as_args: |module_lines, args| { for (module, lines) in module_lines { - for line in lines.iter() { + for line in lines { args.push("--module-raw-line".to_owned()); args.push(module.clone().into()); args.push(line.clone().into()); @@ -1234,6 +1292,11 @@ options! { // This field is handled specially inside the macro. as_args: ignore, }, + /// The set of arguments to be passed straight through to Clang for the macro fallback code. + fallback_clang_args: Vec> { + methods: {}, + as_args: ignore, + }, /// Tuples of unsaved file contents of the form (name, contents). input_header_contents: Vec<(Box, Box)> { methods: { @@ -1263,6 +1326,9 @@ options! { parse_callbacks: Vec> { methods: { /// Add a new [`ParseCallbacks`] instance to configure types in different situations. + /// + /// This can also be used with [`CargoCallbacks`](struct@crate::CargoCallbacks) to emit + /// `cargo:rerun-if-changed=...` for all `#include`d header files. pub fn parse_callbacks(mut self, cb: Box) -> Self { self.options.parse_callbacks.push(Rc::from(cb)); self @@ -1418,10 +1484,8 @@ options! { /// Note that they will usually not work. However you can use `-fkeep-inline-functions` /// or `-fno-inline-functions` if you are responsible of compiling the library to make /// them callable. - #[cfg_attr( - feature = "experimental", - doc = "\nCheck the [`Builder::wrap_static_fns`] method for an alternative." - )] + /// + /// Check the [`Builder::wrap_static_fns`] method for an alternative. pub fn generate_inline_functions(mut self, doit: bool) -> Self { self.options.generate_inline_functions = doit; self @@ -1608,9 +1672,26 @@ options! { args.push(rust_target.to_string()); }, }, + /// The Rust edition to use for code generation. + rust_edition: Option { + methods: { + /// Specify the Rust target edition. + /// + /// The default edition is the latest edition supported by the chosen Rust target. + pub fn rust_edition(mut self, rust_edition: RustEdition) -> Self { + self.options.rust_edition = Some(rust_edition); + self + } + } + as_args: |edition, args| { + if let Some(edition) = edition { + args.push("--rust-edition".to_owned()); + args.push(edition.to_string()); + } + }, + }, /// Features to be enabled. They are derived from `rust_target`. rust_features: RustFeatures { - default: RustTarget::default().into(), methods: {}, // This field cannot be set from the CLI, as_args: ignore, @@ -1980,7 +2061,20 @@ options! { }, as_args: "--wrap-unsafe-ops", }, - /// Patterns for functions whose ABI should be overriden. + /// Use DSTs to represent structures with flexible array members. + flexarray_dst: bool { + methods: { + /// Use DSTs to represent structures with flexible array members. + /// + /// This option is disabled by default. + pub fn flexarray_dst(mut self, doit: bool) -> Self { + self.options.flexarray_dst = doit; + self + } + }, + as_args: "--flexarray-dst", + }, + /// Patterns for functions whose ABI should be overridden. abi_overrides: HashMap { methods: { regex_option! { @@ -1999,7 +2093,7 @@ options! { for (abi, set) in overrides { for item in set.get_items() { args.push("--override-abi".to_owned()); - args.push(format!("{}={}", item, abi)); + args.push(format!("{item}={abi}")); } } }, @@ -2007,7 +2101,6 @@ options! { /// Whether to generate wrappers for `static` functions. wrap_static_fns: bool { methods: { - #[cfg(feature = "experimental")] /// Set whether to generate wrappers for `static`` functions. /// /// Passing `true` to this method will generate a C source file with non-`static` @@ -2026,7 +2119,6 @@ options! { /// The suffix to be added to the function wrappers for `static` functions. wrap_static_fns_suffix: Option { methods: { - #[cfg(feature = "experimental")] /// Set the suffix added to the wrappers for `static` functions. /// /// This option only comes into effect if `true` is passed to the @@ -2043,7 +2135,6 @@ options! { /// The path of the file where the wrappers for `static` functions will be emitted. wrap_static_fns_path: Option { methods: { - #[cfg(feature = "experimental")] /// Set the path for the source code file that would be created if any wrapper /// functions must be generated due to the presence of `static` functions. /// @@ -2104,5 +2195,92 @@ options! { } }, as_args: "--emit-diagnostics", + }, + /// Whether to use Clang evaluation on temporary files as a fallback for macros that fail to + /// parse. + clang_macro_fallback: bool { + methods: { + /// Use Clang as a fallback for macros that fail to parse using `CExpr`. + /// + /// This uses a workaround to evaluate each macro in a temporary file. Because this + /// results in slower compilation, this option is opt-in. + pub fn clang_macro_fallback(mut self) -> Self { + self.options.clang_macro_fallback = true; + self + } + }, + as_args: "--clang-macro-fallback", } + /// Path to use for temporary files created by clang macro fallback code like precompiled + /// headers. + clang_macro_fallback_build_dir: Option { + methods: { + /// Set a path to a directory to which `.c` and `.h.pch` files should be written for the + /// purpose of using clang to evaluate macros that can't be easily parsed. + /// + /// The default location for `.h.pch` files is the directory that the corresponding + /// `.h` file is located in. The default for the temporary `.c` file used for clang + /// parsing is the current working directory. Both of these defaults are overridden + /// by this option. + pub fn clang_macro_fallback_build_dir>(mut self, path: P) -> Self { + self.options.clang_macro_fallback_build_dir = Some(path.as_ref().to_owned()); + self + } + }, + as_args: "--clang-macro-fallback-build-dir", + } + /// Whether to always report C++ "deleted" functions. + generate_deleted_functions: bool { + methods: { + /// Set whether to generate C++ functions even marked "=deleted" + /// + /// Although not useful to call these functions, downstream code + /// generators may need to know whether they've been deleted in + /// order to determine the relocatability of a C++ type + /// (specifically by virtue of which constructors exist.) + pub fn generate_deleted_functions(mut self, doit: bool) -> Self { + self.options.generate_deleted_functions = doit; + self + } + + }, + as_args: "--generate-deleted-functions", + }, + /// Whether to always report C++ "pure virtual" functions. + generate_pure_virtual_functions: bool { + methods: { + /// Set whether to generate C++ functions that are pure virtual. + /// + /// These functions can't be called, so the only reason + /// to generate them is if downstream postprocessors + /// need to know of their existence. This is necessary, + /// for instance, to determine whether a type itself is + /// pure virtual and thus can't be allocated. + /// Downstream code generators may choose to make code to + /// allow types to be allocated but need to avoid doing so + /// if the type contains pure virtual functions. + pub fn generate_pure_virtual_functions(mut self, doit: bool) -> Self { + self.options.generate_pure_virtual_functions = doit; + self + } + + }, + as_args: "--generate-pure-virtual-functions", + }, + /// Whether to always report C++ "private" functions. + generate_private_functions: bool { + methods: { + /// Set whether to generate C++ functions that are private. + /// + /// These functions can't be called, so the only reason + /// to generate them is if downstream postprocessors + /// need to know of their existence. + pub fn generate_private_functions(mut self, doit: bool) -> Self { + self.options.generate_private_functions = doit; + self + } + + }, + as_args: "--generate-private-functions", + }, } diff --git a/bindgen/regex_set.rs b/bindgen/regex_set.rs index b78424aae1..32279557b5 100644 --- a/bindgen/regex_set.rs +++ b/bindgen/regex_set.rs @@ -6,7 +6,7 @@ use std::cell::Cell; /// A dynamic set of regular expressions. #[derive(Clone, Debug, Default)] -pub struct RegexSet { +pub(crate) struct RegexSet { items: Vec>, /// Whether any of the items in the set was ever matched. The length of this /// vector is exactly the length of `items`. @@ -17,18 +17,13 @@ pub struct RegexSet { } impl RegexSet { - /// Create a new RegexSet - pub fn new() -> RegexSet { - RegexSet::default() - } - /// Is this set empty? - pub fn is_empty(&self) -> bool { + pub(crate) fn is_empty(&self) -> bool { self.items.is_empty() } /// Insert a new regex into this set. - pub fn insert(&mut self, string: S) + pub(crate) fn insert(&mut self, string: S) where S: AsRef, { @@ -38,13 +33,13 @@ impl RegexSet { } /// Returns slice of String from its field 'items' - pub fn get_items(&self) -> &[Box] { + pub(crate) fn get_items(&self) -> &[Box] { &self.items } /// Returns an iterator over regexes in the set which didn't match any /// strings yet. - pub fn unmatched_items(&self) -> impl Iterator { + pub(crate) fn unmatched_items(&self) -> impl Iterator { self.items.iter().enumerate().filter_map(move |(i, item)| { if !self.record_matches || self.matched[i].get() { return None; @@ -54,28 +49,29 @@ impl RegexSet { }) } - /// Construct a RegexSet from the set of entries we've accumulated. + /// Construct a `RegexSet` from the set of entries we've accumulated. /// /// Must be called before calling `matches()`, or it will always return /// false. #[inline] - pub fn build(&mut self, record_matches: bool) { - self.build_inner(record_matches, None) + #[allow(unused)] + pub(crate) fn build(&mut self, record_matches: bool) { + self.build_inner(record_matches, None); } #[cfg(all(feature = "__cli", feature = "experimental"))] - /// Construct a RegexSet from the set of entries we've accumulated and emit diagnostics if the + /// Construct a `RegexSet` from the set of entries we've accumulated and emit diagnostics if the /// name of the regex set is passed to it. /// /// Must be called before calling `matches()`, or it will always return /// false. #[inline] - pub fn build_with_diagnostics( + pub(crate) fn build_with_diagnostics( &mut self, record_matches: bool, name: Option<&'static str>, ) { - self.build_inner(record_matches, name) + self.build_inner(record_matches, name); } #[cfg(all(not(feature = "__cli"), feature = "experimental"))] @@ -90,7 +86,7 @@ impl RegexSet { record_matches: bool, name: Option<&'static str>, ) { - self.build_inner(record_matches, name) + self.build_inner(record_matches, name); } fn build_inner( @@ -98,12 +94,12 @@ impl RegexSet { record_matches: bool, _name: Option<&'static str>, ) { - let items = self.items.iter().map(|item| format!("^({})$", item)); + let items = self.items.iter().map(|item| format!("^({item})$")); self.record_matches = record_matches; self.set = match RxSet::new(items) { Ok(x) => Some(x), Err(e) => { - warn!("Invalid regex in {:?}: {:?}", self.items, e); + warn!("Invalid regex in {:?}: {e:?}", self.items); #[cfg(feature = "experimental")] if let Some(name) = _name { invalid_regex_warning(self, e, name); @@ -114,14 +110,13 @@ impl RegexSet { } /// Does the given `string` match any of the regexes in this set? - pub fn matches(&self, string: S) -> bool + pub(crate) fn matches(&self, string: S) -> bool where S: AsRef, { let s = string.as_ref(); - let set = match self.set { - Some(ref set) => set, - None => return false, + let Some(ref set) = self.set else { + return false; }; if !self.record_matches { @@ -132,7 +127,7 @@ impl RegexSet { if !matches.matched_any() { return false; } - for i in matches.iter() { + for i in &matches { self.matched[i].set(true); } @@ -180,20 +175,20 @@ fn invalid_regex_warning( diagnostic.with_title( "Error while parsing a regular expression.", - Level::Warn, + Level::Warning, ); } else { - diagnostic.with_title(string, Level::Warn); + diagnostic.with_title(string, Level::Warning); } } err => { let err = err.to_string(); - diagnostic.with_title(err, Level::Warn); + diagnostic.with_title(err, Level::Warning); } } diagnostic.add_annotation( - format!("This regular expression was passed via `{}`.", name), + format!("This regular expression was passed via `{name}`."), Level::Note, ); diff --git a/bindgen/time.rs b/bindgen/time.rs index c13a640c46..2952e36f76 100644 --- a/bindgen/time.rs +++ b/bindgen/time.rs @@ -29,23 +29,23 @@ impl<'a> Timer<'a> { /// Returns the time elapsed since the timer's creation pub fn elapsed(&self) -> Duration { - Instant::now() - self.start + self.start.elapsed() } fn print_elapsed(&mut self) { if self.output { let elapsed = self.elapsed(); let time = (elapsed.as_secs() as f64) * 1e3 + - (elapsed.subsec_nanos() as f64) / 1e6; + f64::from(elapsed.subsec_nanos()) / 1e6; let stderr = io::stderr(); // Arbitrary output format, subject to change. - writeln!(stderr.lock(), " time: {:>9.3} ms.\t{}", time, self.name) + writeln!(stderr.lock(), " time: {time:>9.3} ms.\t{}", self.name) .expect("timer write should not fail"); } } } -impl<'a> Drop for Timer<'a> { +impl Drop for Timer<'_> { fn drop(&mut self) { self.print_elapsed(); } diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index dbdf3f700c..daaed04081 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -27,4 +27,5 @@ - [Generating Bindings to Objective-c](./objc.md) - [Using Unions](./using-unions.md) - [Using Bitfields](./using-bitfields.md) +- [Using Flexible Array Members](./using-fam.md) - [FAQ](./faq.md) diff --git a/book/src/code-formatting.md b/book/src/code-formatting.md index 2972a48b4f..368535c452 100644 --- a/book/src/code-formatting.md +++ b/book/src/code-formatting.md @@ -47,8 +47,7 @@ fn main() { assert!( output.status.success(), - "Unsuccessful status code when running `rustup`: {:?}", - output + "Unsuccessful status code when running `rustup`: {output:?}", ); let rustfmt_path = @@ -73,7 +72,7 @@ These two methods also apply to any other toolchain available in your system. The [`prettyplease`](https://github.com/dtolnay/prettyplease) crate is a minimal formatter for generated code. To format bindings using `prettyplease` you have to invoke `bindgen` with either the `--formatter=prettyplease` flag or -the the `bindgen::Builder::formatter(bindgen::Formatter::Prettyplease)`. One of +the `bindgen::Builder::formatter(bindgen::Formatter::Prettyplease)`. One of its advantages is that `prettyplease` can be used in minimal environments where the Rust toolchain is not installed. diff --git a/book/src/cpp.md b/book/src/cpp.md index 9b451b9d35..db368f6787 100644 --- a/book/src/cpp.md +++ b/book/src/cpp.md @@ -154,6 +154,6 @@ instance.assume_init_mut().method(); ``` You can easily verify this fact if you provide a implementation for `MyClass` -and `method` that prints the the `this` pointer address. However, you can +and `method` that prints the `this` pointer address. However, you can ignore this fact if you know that the original C++ code does not rely on the instance address in its internal logic. diff --git a/book/src/faq.md b/book/src/faq.md index e82b4a446a..bbaaab6368 100644 --- a/book/src/faq.md +++ b/book/src/faq.md @@ -8,6 +8,7 @@ - [Does `bindgen` support the C++ Standard Template Library (STL)?](#does-bindgen-support-the-c-standard-template-library-stl) - [How to deal with bindgen generated padding fields?](#how-to-deal-with-bindgen-generated-padding-fields) - [How to generate bindings for a custom target?](#how-to-generate-bindings-for-a-custom-target) +- [Why isn't `bindgen` generating documentation for system headers?](#why-isnt-bindgen-generating-documentation-for-system-headers) @@ -115,3 +116,9 @@ $ bindgen -- --target=armv7a-none-eabi ``` If you are using `bindgen` as a library, you should call `builder.clang_arg("--target=armv7a-none-eabi")` on your `builder`. + +### Why isn't `bindgen` generating documentation for system headers? + +By default, Bindgen does not generate documentation for system headers because +`libclang` does not provide this information. To address this, you should call +`builder.clang_arg("-fretain-comments-from-system-headers")` on your `builder`. diff --git a/book/src/non-system-libraries.md b/book/src/non-system-libraries.md index d5d288d101..598889d360 100644 --- a/book/src/non-system-libraries.md +++ b/book/src/non-system-libraries.md @@ -17,13 +17,9 @@ Given that the library has not been compiled yet, we need to modify the library: ```rust,ignore -extern crate bindgen; - use std::env; use std::path::PathBuf; -use bindgen::CargoCallbacks; - fn main() { // This is the directory where the `c` library is located. let libdir_path = PathBuf::from("hello") @@ -88,7 +84,7 @@ fn main() { .header(headers_path_str) // Tell cargo to invalidate the built crate whenever any of the // included header files changed. - .parse_callbacks(Box::new(CargoCallbacks::new())) + .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) // Finish the builder and generate the bindings. .generate() // Unwrap the Result and panic on failure. diff --git a/book/src/requirements.md b/book/src/requirements.md index b701234fad..cf719a0d61 100644 --- a/book/src/requirements.md +++ b/book/src/requirements.md @@ -7,7 +7,7 @@ This page lists the requirements for running `bindgen` and how to get them. `bindgen` leverages `libclang` to preprocess, parse, and type check C and C++ header files. -It is required to use Clang 5.0 or greater. +It is required to use Clang 9.0 or greater. ### Installing Clang @@ -48,10 +48,10 @@ $ port install clang #### Debian-based Linuxes ```bash -# apt install llvm-dev libclang-dev clang +# apt install libclang-dev ``` -Ubuntu 18.04 provides the necessary packages directly. +If you want to use the function `bindgen::Builder::dump_preprocessed_input`, then you also need the package `clang`. #### Arch @@ -75,13 +75,13 @@ Add `export LIBCLANG_PATH=/usr/local/lib` to your profile. #### From source -If your package manager doesn't yet offer Clang 5.0, you'll need to build from +If your package manager doesn't yet offer Clang 9.0, you'll need to build from source. For that, follow the instructions [here](http://clang.llvm.org/get_started.html). Those instructions list optional steps. For `bindgen`: * Checkout and build clang -* Checkout and build the extra-clang-tools +* Checkout and build `clang-tools-extra` * You do not need to checkout or build compiler-rt * You do not need to checkout or build libcxx diff --git a/book/src/tutorial-1.md b/book/src/tutorial-1.md index 464b6b9d71..a26c393b3b 100644 --- a/book/src/tutorial-1.md +++ b/book/src/tutorial-1.md @@ -10,7 +10,7 @@ You can always check the latest version at ```toml [build-dependencies] -bindgen = "0.65.1" +bindgen = "0.71.0" ``` > ⚠️ **Warning** diff --git a/book/src/tutorial-5.md b/book/src/tutorial-5.md index de91d092a1..8a71dac355 100644 --- a/book/src/tutorial-5.md +++ b/book/src/tutorial-5.md @@ -40,7 +40,7 @@ mod tests { r if r == (BZ_PARAM_ERROR as _) => panic!("BZ_PARAM_ERROR"), r if r == (BZ_MEM_ERROR as _) => panic!("BZ_MEM_ERROR"), r if r == (BZ_OK as _) => {}, - r => panic!("Unknown return value = {}", r), + r => panic!("Unknown return value = {r}"), } // Compress `input` into `compressed_output`. @@ -55,7 +55,7 @@ mod tests { r if r == (BZ_FINISH_OK as _) => panic!("BZ_FINISH_OK"), r if r == (BZ_SEQUENCE_ERROR as _) => panic!("BZ_SEQUENCE_ERROR"), r if r == (BZ_STREAM_END as _) => {}, - r => panic!("Unknown return value = {}", r), + r => panic!("Unknown return value = {r}"), } // Finish the compression stream. @@ -63,7 +63,7 @@ mod tests { match result { r if r == (BZ_PARAM_ERROR as _) => panic!("BZ_PARAM_ERROR"), r if r == (BZ_OK as _) => {}, - r => panic!("Unknown return value = {}", r), + r => panic!("Unknown return value = {r}"), } // Construct a decompression stream. @@ -76,7 +76,7 @@ mod tests { r if r == (BZ_PARAM_ERROR as _) => panic!("BZ_PARAM_ERROR"), r if r == (BZ_MEM_ERROR as _) => panic!("BZ_MEM_ERROR"), r if r == (BZ_OK as _) => {}, - r => panic!("Unknown return value = {}", r), + r => panic!("Unknown return value = {r}"), } // Decompress `compressed_output` into `decompressed_output`. @@ -92,7 +92,7 @@ mod tests { r if r == (BZ_MEM_ERROR as _) => panic!("BZ_MEM_ERROR"), r if r == (BZ_OK as _) => panic!("BZ_OK"), r if r == (BZ_STREAM_END as _) => {}, - r => panic!("Unknown return value = {}", r), + r => panic!("Unknown return value = {r}"), } // Close the decompression stream. @@ -100,7 +100,7 @@ mod tests { match result { r if r == (BZ_PARAM_ERROR as _) => panic!("BZ_PARAM_ERROR"), r if r == (BZ_OK as _) => {}, - r => panic!("Unknown return value = {}", r), + r => panic!("Unknown return value = {r}"), } assert_eq!(input, &decompressed_output[..]); diff --git a/book/src/using-bitfields.md b/book/src/using-bitfields.md index 0ee9f0329c..8929f73705 100644 --- a/book/src/using-bitfields.md +++ b/book/src/using-bitfields.md @@ -8,6 +8,11 @@ As Rust does not support bitfields, Bindgen generates a struct for each with the * For each contiguous block of bitfields, Bindgen emits an opaque physical field that contains one or more logical bitfields * A static constructor ```new_bitfield_{1, 2, ...}``` with a parameter for each bitfield contained within the opaque physical field. +To keep bindgen from generating the bitfield unit struct, it can be blocklisted like any +other type, i.e. `--blocklist-type "__BindgenBitfieldUnit"`. This may be useful if +you want to define a custom implementation, or your generated bindings import a +pre-existing definition for the bitfield unit type. + ## Bitfield examples For this discussion, we will use the following C type definitions and functions. diff --git a/book/src/using-fam.md b/book/src/using-fam.md new file mode 100644 index 0000000000..aaf19c90fd --- /dev/null +++ b/book/src/using-fam.md @@ -0,0 +1,163 @@ +# Using C structures with Flexible Array Members + +Since time immemorial, C programmers have been using what was called "the struct +hack". This is a technique for packing a fixed-size structure and a +variable-sized tail within the same memory allocation. Typically this looks +like: + +```c +struct MyRecord { + time_t timestamp; + unsigned seq; + size_t len; + char payload[0]; +}; +``` + +Because this is so useful, it was standardized in C99 as "flexible array +members", using almost identical syntax: +```c +struct MyRecord { + time_t timestamp; + unsigned seq; + size_t len; + char payload[]; // NOTE: empty [] +}; +``` + +Bindgen supports these structures in two different ways. + +## `__IncompleteArrayField` + +By default, bindgen will generate the corresponding Rust structure: +```rust,ignore +#[repr(C)] +struct MyRecord { + pub timestamp: time_t, + pub seq: ::std::os::raw::c_uint, + pub len: usize, + pub payload: __IncompleteArrayField<::std::os::raw::c_char>, +} +``` + +The `__IncompleteArrayField` type is zero-sized, so this structure represents +the prefix without any trailing data. In order to access that data, it provides +the `as_slice` unsafe method: +```rust,ignore + // SAFETY: there's at least `len` bytes allocated and initialized after `myrecord` + let payload = unsafe { myrecord.payload.as_slice(myrecord.len) }; +``` +There's also `as_mut_slice` which does the obvious. + +These are `unsafe` simply because it's up to you to provide the right length (in +elements of whatever type `payload` is) as there's no way for Rust or Bindgen to +know. In this example, the length is a very straightforward `len` field in the +structure, but it could be encoded in any number of ways within the structure, +or come from somewhere else entirely. + +One big caveat with this technique is that `std::mem::size_of` (or +`size_of_val`) will *only* include the size of the prefix structure. if you're +working out how much storage the whole structure is using, you'll need to add +the suffix yourself. + +## Using Dynamically Sized Types + +If you invoke bindgen with the `--flexarray-dst` option, it will generate +something not quite like this: + +```rust,ignore +#[repr(C)] +struct MyRecord { + pub timestamp: time_t, + pub seq: ::std::os::raw::c_uint, + pub len: usize, + pub payload: [::std::os::raw::c_char], +} +``` +Rust has a set of types which are almost exact analogs for these Flexible Array +Member types: the Dynamically Sized Type ("DST"). + +This looks almost identical to a normal Rust structure, except that you'll note +the type of the `payload` field is a raw slice `[...]` rather than the usual +reference to slice `&[...]`. + +That `payload: [c_char]` is telling Rust that it can't directly know the total +size of this structure - the `payload` field takes an amount of space that's +determined at runtime. This means you can't directly use values of this type, +only references: `&MyRecord`. + +In practice, this is very awkward. So instead, bindgen generates: +```rust,ignore +#[repr(C)] +struct MyRecord { + pub timestamp: time_t, + pub seq: ::std::os::raw::c_uint, + pub len: usize, + pub payload: FAM, +} +``` + +That is: +1. a type parameter `FAM` which represents the type of the `payload` field, +2. it's `?Sized` meaning it can be unsized (ie, a DST) +3. it has the default type of `[c_char; 0]` - that is a zero-sized array of characters + +This means that referencing plain `MyRecord` will be exactly like `MyRecord` +with `__IncompleteArrayField`: it is a fixed-sized structure which you can +manipulate like a normal Rust value. + +But how do you get to the DST part? + +Bindgen will also implement a set of helper methods for this: + +```rust,ignore +// Static sized variant +impl MyRecord<[::std::os::raw::c_char; 0]> { + pub unsafe fn flex_ref(&self, len: usize) -> &MyRecord<[::std::os::raw::c_char]> { ... } + pub unsafe fn flex_mut_ref(&mut self, len: usize) -> &mut MyRecord<[::std::os::raw::c_char]> { ... } + // And some raw pointer variants +} +``` +These will take a sized `MyRecord<[c_char; 0]>` and a length in elements, and +return a reference to a DST `MyRecord<[c_char]>` where the `payload` field is a +fully usable slice of `len` characters. + +The magic here is that the reference is a fat pointer, which not only encodes +the address, but also the dynamic size of the final field, just like a reference +to a slice is. This means that you get full bounds checked access to the +`payload` field like any other Rust slice. + +It also means that doing `mem::size_of_val(myrecord)` will return the *complete* +size of this structure, including the suffix. + +You can go the other way: +```rust,ignore +// Dynamic sized variant +impl MyRecord<[::std::os::raw::c_char]> { + pub fn fixed(&self) -> (&MyRecord<[::std::os::raw::c_char; 0]>, usize) { ... } + pub fn fixed_mut(&mut self) -> (&mut MyRecord<[::std::os::raw::c_char; 0]>, usize) { ... } + pub fn layout(len: usize) -> std::alloc::Layout { ... } +} +``` +which takes the DST variant of the structure and returns the sized variant, +along with the number of elements are after it. These are all completely safe +because all the information needed is part of the fat `&self` reference. + +The `layout` function takes a length and returns the `Layout` - that is, size +and alignment, so that you can allocate memory for the structure (for example, +using `malloc` so you can pass it to a C function). + +Unfortunately the language features needed to support these methods are still unstable: +- [ptr_metadata](https://doc.rust-lang.org/beta/unstable-book/library-features/ptr-metadata.html), + which enables all the fixed<->DST conversions, and +- [layout_for_ptr](https://doc.rust-lang.org/beta/unstable-book/library-features/layout-for-ptr.html), + which allows he `layout` method + +As a result, if you don't specify `--rust-target nightly` you'll just get the +bare type definitions, but no real way to use them. It's often convenient to add +the +```bash +--raw-line '#![feature(ptr_metadata,layout_for_ptr)]' +``` +option if you're generating Rust as a stand-alone crate. Otherwise you'll need +to add the feature line to your containing crate. diff --git a/book/src/using-unions.md b/book/src/using-unions.md index 9e8e9b99d7..5ae764a33d 100644 --- a/book/src/using-unions.md +++ b/book/src/using-unions.md @@ -66,11 +66,11 @@ When using the `union` builtin type, there are two choices for initialization: mod bindings_builtin_union; fn union_builtin() { - // Initalize the union to zero + // Initialize the union to zero let x = bindings_builtin_union::greek_t::default(); // If `--with-derive-default` option is not used, the following may be used - // to initalize the union to zero: + // to initialize the union to zero: let x = unsafe { std::mem::zeroed::() }; // Or, it is possible to initialize exactly one variant of the enum: diff --git a/ci/test.sh b/ci/test.sh index 11e091f49f..ae93f2ad1d 100755 --- a/ci/test.sh +++ b/ci/test.sh @@ -8,64 +8,15 @@ set -x # Give a pipeline a non-zero exit code if one of its constituents fails set -o pipefail -function llvm_linux_target_triple() { - case "$1" in - 9.0.1) echo "x86_64-linux-gnu-ubuntu-16.04" ;; - *) echo "x86_64-linux-gnu-ubuntu-18.04" ;; - esac -} - -function llvm_macos_target_triple() { - case "$1" in - 9.0.1) echo "x86_64-apple-darwin" ;; - *) echo "arm64-apple-darwin22.0" ;; - esac -} - -function llvm_version_triple() { - case "$1" in - 9.0) echo "9.0.1" ;; - # By default, take the .0 patch release - *) echo "$1.0" ;; - esac -} - -function llvm_base_url() { - local llvm_version_triple=$1 - echo "https://github.com/llvm/llvm-project/releases/download/llvmorg-$llvm_version_triple" -} - -function llvm_download() { - local base_url=$1 - local arch=$2 - - export LLVM=clang+llvm-${LLVM_VERSION_TRIPLE}-$arch - export LLVM_DIRECTORY="$HOME/.llvm/${LLVM}" - - if [ -d "${LLVM_DIRECTORY}" ]; then - echo "Using cached LLVM download for ${LLVM}..." - else - wget --no-verbose $base_url/${LLVM}.tar.xz - mkdir -p "${LLVM_DIRECTORY}" - tar xf ${LLVM}.tar.xz -C "${LLVM_DIRECTORY}" --strip-components=1 - fi - - export LIBCLANG_PATH="${LLVM_DIRECTORY}/lib" - export LLVM_CONFIG_PATH="${LLVM_DIRECTORY}/bin/llvm-config" -} - -# Download and set up a sane LLVM version set_llvm_env() { - export LLVM_VERSION_TRIPLE=`llvm_version_triple ${LLVM_VERSION}` - local base_url=`llvm_base_url ${LLVM_VERSION_TRIPLE}` - - if [ "$GITHUB_ACTIONS_OS" == "ubuntu-latest" ]; then - llvm_download $base_url `llvm_linux_target_triple ${LLVM_VERSION_TRIPLE}` - export LD_LIBRARY_PATH="${LLVM_DIRECTORY}/lib":${LD_LIBRARY_PATH:-} - else - llvm_download $base_url `llvm_macos_target_triple ${LLVM_VERSION_TRIPLE}` - export DYLD_LIBRARY_PATH="${LLVM_DIRECTORY}/lib":${DYLD_LIBRARY_PATH:-} - fi + export LLVM_CONFIG_PATH=${LLVM_PATH}/bin/llvm-config + echo "LLVM_CONFIG_PATH=$LLVM_CONFIG_PATH" + + export LIBCLANG_PATH=${LLVM_PATH}/lib/ + echo "LIBCLANG_PATH=$LIBCLANG_PATH" + + export CLANG_PATH=${LLVM_PATH}/bin/clang + echo "CLANG_PATH=$CLANG_PATH" } assert_no_diff() { @@ -74,13 +25,8 @@ assert_no_diff() { git diff-index --quiet HEAD } -set_llvm_env - get_cargo_args() { local args="" - if [ ! -z "$RUST_TARGET" ]; then - args+=" --target $RUST_TARGET" - fi if [ "$BINDGEN_RELEASE_BUILD" == "1" ]; then args+=" --release" fi @@ -100,21 +46,93 @@ get_cargo_args() { echo $args } -if [ ! -z "$RUST_CROSS_COMPILER" ]; then - export RUSTFLAGS="-C linker=${RUST_CROSS_COMPILER}-gcc" -fi +set_llvm_env CARGO_ARGS=`get_cargo_args` # Ensure we build without warnings RUSTFLAGS="-Dwarnings" cargo check $CARGO_ARGS -if [ "$BINDGEN_MAIN_TESTS" == "1" ]; then - # Run the tests - (cd bindgen-tests && cargo test $CARGO_ARGS) -fi +# Run the tests +(cd bindgen-tests && cargo test $CARGO_ARGS) assert_no_diff # Run the integration tests (cd bindgen-integration && cargo test $CARGO_ARGS) + +if [ "$BINDGEN_RUST_FOR_LINUX_TEST" == "1" ]; then + # Run the Rust for Linux test + # + # This is intended to be an end-to-end test that runs what Linux kernel + # developers/users would do. It is a quick, build-only test of the Rust code + # in the Linux kernel. + + # Put LLVM binaries in the path for `LLVM=1`. The LLVM `bin` directory should + # go first since there are others in the Ubuntu image. + export PATH="${LLVM_PATH}/bin:${PATH}" + + # Kernel build dependency: `bindgen-cli`, which is under test. + # + # Using `cargo build` (and adding the two common profiles to the `$PATH`) so + # that we can use `$CARGO_ARGS` as is, since `cargo install` does not support + # `--release`. `--target-dir` is used to isolate from other possible tests. + # A cleaner alternative is using `--out-dir`, but it is unstable. + (cd bindgen-cli && cargo build --target-dir ${HOME}/.bindgen $CARGO_ARGS) + export PATH="${HOME}/.bindgen/release:${HOME}/.bindgen/debug:${PATH}" + + # Kernel build dependency: `libelf-dev`. + sudo apt-get update + sudo apt-get install libelf-dev + + # Kernel build dependency: the Rust standard library sources. + # + # `rustup` is used here to install the `rust-src` component (instead of using + # `actions-rs/toolchain`'s `components` option in the workflow step) since we + # only need it for this test, and anyway the action installs `rustup`. + rustup component add rust-src + + # Ideally this should be updated from time to time (e.g. every kernel `-rc1`), + # and each update should only contain this change. + # + # Both commit hashes and tags are supported. + LINUX_VERSION=v6.14 + + # Download Linux at a specific commit + mkdir -p linux + git -C linux init + git -C linux remote add origin https://github.com/torvalds/linux.git + git -C linux fetch --depth 1 origin ${LINUX_VERSION} + git -C linux checkout FETCH_HEAD + + # Configure Rust for Linux + cat < linux/kernel/configs/rfl-for-bindgen-ci.config +# CONFIG_WERROR is not set + +CONFIG_RUST=y + +CONFIG_SAMPLES=y +CONFIG_SAMPLES_RUST=y + +CONFIG_SAMPLE_RUST_MINIMAL=m +CONFIG_SAMPLE_RUST_PRINT=y + +CONFIG_RUST_PHYLIB_ABSTRACTIONS=y +CONFIG_AX88796B_PHY=y +CONFIG_AX88796B_RUST_PHY=y + +CONFIG_KUNIT=y +CONFIG_RUST_KERNEL_DOCTESTS=y +EOF + + make -C linux LLVM=1 -j$(($(nproc) + 1)) \ + rustavailable \ + defconfig \ + rfl-for-bindgen-ci.config + + # Build Rust for Linux + make -C linux LLVM=1 -j$(($(nproc) + 1)) \ + samples/rust/rust_minimal.o \ + samples/rust/rust_print_main.o \ + drivers/net/phy/ax88796b_rust.o +fi diff --git a/dist-workspace.toml b/dist-workspace.toml new file mode 100644 index 0000000000..3a0f7c2c75 --- /dev/null +++ b/dist-workspace.toml @@ -0,0 +1,25 @@ +[workspace] +members = ["cargo:."] + +# Config for 'cargo dist' +[dist] +# The preferred cargo-dist version to use in CI (Cargo.toml SemVer syntax) +cargo-dist-version = "0.22.1" +# CI backends to support +ci = "github" +# The installers to generate for each app +installers = ["shell"] +# Target platforms to build apps for (Rust target-triple syntax) +targets = ["aarch64-apple-darwin", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu"] +# Whether to consider the binaries in a package for distribution (defaults true) +dist = false +# Which actions to run on pull requests +pr-run-mode = "plan" +# Whether to install an updater program +install-updater = false +# Path that installers should place binaries in +install-path = "CARGO_HOME" + +[dist.github-custom-runners] +aarch64-apple-darwin = "macos-14" +x86_64-apple-darwin = "macos-13"